ASP developed in November 1996by Microsoft. An ASP file cancontain text, HTML tags andscripts. Scripts in an ASP file areexecuted on the server.
1. ASP stands for Active Server Pages2. ASP is a program that runs inside IIS3. IIS stands for Internet Information Services4. IIS comes as a free component with Windows 20005. IIS is also a part of the Windows NT 4.0 Option Pack6. The Option Pack can be downloaded from Microsoft7. PWS is a smaller - but fully functional - version of IIS8. PWS can be found on your Windows 95/98 CD
• Dynamically edit, change or add any content of a Web page• Respond to user queries or data submitted from HTML forms• Access any data or databases and return the results to a browser
• Customize a Web page to make it more useful for individual users• The advantages of using ASP instead of CGI and Perl, are those of simplicity and speed• Provide security since your ASP code can not be viewed from the browser• Clever ASP programming can minimize the network traffic
ASP is a mixture of HTML and scriptingthat enables you to build dynamic and database-driven web sites.ASP is a server - side scripting environmentthat we can use to create and run dynamic,interactive, high - performance Web serverapplications."
A server is a computer (Usually high-end, "Faster,Bigger") that allows computers in a network to havea shared resource.Most servers in the area are used toshare filesto run programsor to share PrintersThe different rolls that servers play in the area are:
PDC (Primary Domain Controller)These servers are the bosses of 1 or more servers.All usernames and passwords are kept on the PDC.BDC (Backup Domain Controller)These servers are the backups which take over if the PDC fails.They keep a copy of the Usernames and Passwords tovalidate logons incase the PDC is busy.ServerThese servers are just ordinary servers that can join a domainbut can not replace a PDC like a BDC.These servers usually are setup to just share files or printers.
Print ServerThese servers are usually assigned network printersto share and maintain.File ServersThese servers have folders/directories sharedfor access by network users.Application ServersThese servers have programs that are sharedacross the network to multiple computers. A server can only be one of these but can be any combination of file, print, and application server
A protocol is a set of rules that governs thecommunications between computerson a network.These rules include guidelines that regulate the following characteristics of a networkaccess method, allowed physical space, types of cabling, and speed of data transfer. The most common protocols are: Ethernet Local Talk Token Ring FDDI ATM
HTTP (Hypertext Transfer Protocol)is the set of rules for transferring files(text, graphic images, sound, video, and othermultimedia files) on the World Wide Web.As soon as a Web user opens their Web browser, the user is indirectly making use of HTTP.
PWS is for older Windows system like Windows 95, 98, and NT.PWS is easy to install and can be used for developing and testing web applications including ASP.
Open the Add-ons folder on your Windows98 CD, find the PWS folder and run the setup.exe file.An Inetpub folder will be created on your hard drive. Open it and find the wwwroot folder.Create a new folder, like "MyWeb", under wwwroot.Use a text editor to write some ASP code,save the file as "test1.asp" in the "MyWeb" folder.Make sure your Web server is running –The installation program has added a new icon on your task bar this is the PWS symbol). Click on the icon and press the Startbutton in the window that appears.Open your browser and type in http://localhost/MyWeb/test1.asp", to view your first ASP page.
Note: You cannot run ASP on Windows XP Home Edition. Insert the Windows XP Professional CD-Rom into your CD-Rom Drive From your Start Button, go to Settings, and Control Panel In the Control Panel window select Add/Remove Programs In the Add/Remove window select Add/Remove Windows ComponentsIn the Wizard window check Internet Information Services , click OK
An Inetpub folder will be created on your hard driveOpen the Inetpub folder, and find a folder named wwwrootCreate a new folder , like "MyWeb", under wwwroot.Use a text editor to write some ASP code, save the fileas "test1.asp" in the "MyWeb" folderMake sure your Web server is running - its status can bechecked by going into the Control Panel,then Administrative Tools , and double-clickthe "IIS Manager" iconOpen your browser and typein "http://localhost/MyWeb/test1.asp", to view your first ASP page
Client/server model is a concept for describing communications between computing processes that are classified as service consumers (clients) and service providers (servers).
Client/server describes the relationship between two computer programs in which one program, the client, makes a service request from another program, the server, which fulfills the request
Requestclient server Response
A scripting language has a particularsyntax used to execute commands on acomputer. A program composed ofcommands from a particular scriptinglanguage is referred to as a script.
Server-side scripts are processed completely on the web server.The client does not receive any code fromserver-side scripts; rather, the client receives just the output of the server-side scripts.Client-side scripts and server side scripts cannot interact with one another because theclient – side scripts are executed on the client,after the server-side scripts have finishedprocessing completely.ASP script is a server side scripting.
In order to activate ASP componentsand to use its objects, a script is placedon the Web page along with the HTMLcodes specifying how the generatedinformation is to be formatted for displayin the browser.This script is written in the VBScriptlanguage and is contained inside thespecial symbols <% and %>to indicate its presence to the server:
<%This is a script%>
After you have installed IIS or PWS follow these steps:1. Look for a new folder called Inetpub on your hard drive2.Open the Inetpub folder, and find a folder named wwwroot
3. Write some ASP code and save the file as “first.asp" in the new folder4. Make sure your Web server is running
6. Open your browser and type "http://localhost/first.asp", to view your first web page
Response.write command is justlike the printf command in C. Theresponse.write command is usedto write output to a browser. Thefollowing example sends the text “MyFirst ASP Program !" to the browser:
<html> <head><title>First ASP Program</title></head><body> <% response.write(“My First ASP Program !") %> </body> </html>
<%response.write "Hello ASP World<br>"response.write "Today is " & Dateresponse.write " and the time is " & Time%>
ASP uses VBScript as its defaultprogramming language. This meansVBScript comments are ASPcomments. That means there isnt anysupport for multiple line commentsthat you see in HTML and variousother programming languages.
To create comment in ASP you simply place an apostrophe ‘ in front of what you want to make a comment. <% ‘This is a comment Response.write(“this is a comment”) %>
When the server invokes the ASP scriptingengine, it parse the file and inserts anyinclude files. It then collects the scriptportion by finding all the scriptdelimiter.The ASP treats all non-scriptcontents as strings that it writesverbatim(Exactly) back to the client. Nextthe scripting engine creates variables andexternal components invoked by the script.Finally it begins the script executing eachcommand and sending results to the client.
Request ASP.DLL ASP Scripting Engine Response HTML Coding ProcessingClient Server
The process of ASP script is goes through these five stages1. Request: The web browser contacts the server and tells it what page it wants to see2. Pre-processing : The asp.dill file does some initial processing on the requested script.3. Execution : The scripting engine executes the instructions in the script4. Translate: ASP translate the result of the execution into HTML5. Display: The HTML is sent back to the browser,which process the tags and display it.
•A variable is used to store information for later use.•ASP is not a language in itself. To program ASP youactually need to know the VBScript scripting language.This means that all VBScript variable rules can beapplied to your ASP code.•In ASP you declare a variable with the use of the Dimkeyword, which is short for Dimension.•(Dimension in English refers to the amount of spacesomething takes up in the real world, but incomputer terms it refers to space in computermemory.)
The value of each variable is held in the servers memory, so the value of the variable can be manipulated or displayed as needed within a page. In VBScript, there is only one data type, and that is variant. A variant can hold either strings or numbers, and will behave as a number if its numeric, and as a string for string values. In ASP, it is not necessary to declare your variables before using them. If, however, you choose to do so, you use the DIM statement
ASP Variable Naming Conventions Once again, ASP uses VBScript by default and so it also uses VBScripts variable naming conventions. These rules are:1. Variable name must start with an alphabetic character (A through Z or a through z)2. Variables cannot contain a period3. Variables cannot be longer than 255 characters (dont think thatll be a problem!)4. Variables must be unique in the scope in which it is declared.
Assigning values in ASP is straightforward enough,just use the equals "=" operator. Ahead we have set avariable equal to a number and a separate variableequal to a string.
A variable declared outside a procedure can be accessed and changed by any script in the ASP file. A variable declared inside a procedure is created and destroyed every time the procedure is executed. No scripts outside the procedure can access or change the variable. To declare variables accessible to more than one ASP file, declare them as session variables or application variables.
Session Variables Sessionvariables 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.
<% Note that lines starting with a single quote are comments. Commented lines are not executed. First, declare variables using Dim. This is optionalDim a, b, c, d, e, fa=1b=2c= a + bd="The value of "e=" plus "f=" equals "response.write (d & a & e & b & f & c)%> The script output is: The value of 1 plus 2 equals 3
<html><body><%dim namename=" Mickey Mouse "response .write ("My name is: " & name)%></body></html>
Comparison operators are used when youwant to compare two values to make adecision. Comparison operators are mostcommonly used in conjunction with"If...Then" and "While statements, otherwise known as conditional statements.The items that are most often compared arenumbers.The result of a comparison operator is eitherTRUE or FALSE.
A logical operator is used for complexstatements that mustmake decisions based on one or more ofthese truth values.
The only string operator is the string concatenationoperator "&" that takestwo strings and join them together to form a new string.An example would bestring1 = "Tim" and string2 = " is a Hero".The following code would combine these two strings intoone: string3 = string1 & string2
A control structure is a programming structurethat allows your program to make decisions.Types of controlsThere are three major types of controls structures1. Conditional logic2. Looping logic3. Branching logic
Conditional logic allows you to match conditionif condition matches then result come if conditionnot matches result not comeExampleIn job selection form if age is less then 27 then you canfill formorif age is more then 27 then you are not eligible forthis job.
<%Dim ResultResult = 70if Result >= 57 then response.write("Pass")else response.write("Fail")end if%>
<%Dim ResultResult = 70if Result >= 75 then response.write("Passed: Grade A ")elseif Result >= 60 then response.write("Passed: Grade B ")elseif Result >= 45 then response.write("Passed: Grade C ")else response.write("Failed ")end if%>
<%@ language="vbscript“%><%Dim FlowerFlower = "rose"select case flower case "rose" response.write(flower & " costs 20rs") case "daisy" response.write(flower & " costs 15rs") case "orchild" response.write(flower & " costs 12rs") case else response.write("There is no such flower in our shop")end select%>
ASP performs several types of repetitive operations,called "looping".Loops are set of instructions used to repeat the sameblock of code till a specified condition returns falseor true depending on how you need it.To control the loops you can use counter variablethat increments or decrements with each repetitionof the loop.
<%@ language="vbscript" %><%For i = 0 to 10 response.write("The number is " & i &"<br>")Next%>
<%@ language="vbscript" %><%response.write("<h1>Multiplication table</h1>")response.write("<table border=2 width=50>")Dim iFor i=1 to 10response.write("<tr>")response.write("<td>"& i &"</td>")Dim jFor j=2 to 43response.write("<td>"&i * j &"</td>")Nextresponse.write("</tr>")Nextresponse.write("</table>")%>
<%Dim ii=0Do While i<=10 response. write( i & "<br>") i=i+1Loop%>
<%a=1Do while a < 11 response.write "This is loop " & a & "<br>" a=a+1Loop%><%a=1Do until a = 11 response.write "This is loop " & a & "<br>" a=a+1Loop%>
<%a=1Do until a = 11 If a < 6 then response.write "This is loop " & a & "<br>" a=a+1 Else Exit Do End IfLoop%>
The branch logic control refers to the process of leaving the current flow of the program to a new set of instructions. There are two types of branching logic controls: subroutines (procedure) and functions. The subroutines perform actions and functions compute values. We first start with subroutines.
Functions are written to perform calculations. Like subroutines, functions can take one or more arguments. Functions can also return one value. A function begins with the keyword function and ends with the keyword END FUNCTION. FUNCTION AbValue (inNo) If inNo < 0 then inNo = - inNo END IF AbValue = inNo END FUNCTION The value that is returned by a function can be printed or assigned to another variable for later use in the program.
Functions and sub procedures have manysimilarities:• They can be called or invoked from anywhere within yourscript.•A function or sub procedure can be reused as many timesas required, thus saving you time writing out repetitivecode Both are blocks of self contained code that canaccept arguments.•Both will only run when called or invoked from codeelsewhere and will not run automatically when the page isloaded. The difference between a function and a sub is thata sub will do some stuff (like printing something to thescreen) and then quit, while a function runs some codeand then returns the result back to the code that called it.•A Function could be used to do a calculation and thenreturn a result.
<html><head><%sub name()response.write (“My name is Hunter")end sub%></head><body><%response.write(“Welcome today is Monday")response.write("<br>")call nameresponse.write("<br>")response.write("thanks")%></body></html>
<html><head><%function sum (x,y)sum=x+yend function%></head><body><%dim x,y,zx=20y=40z=sum(x,y)response.write ("sum is " & z)%></body></html>
Vb Scri pt arra y is 0 base d, mea ning that the arra y elem ent inde
static array remains with fixed size throughout their life open. To use static array you need to know upfront the maximum number of the elements this array will contain. If you need more flexible vb script array with variable index size, then you can use dynamic array.Dynamic array index size can be increased/decreased during their life span.
Create static array called “arrcar” that will hold the name of five cars. <% Dim arrcar arrcar=Array("Audi","Honda city","Mercedes","Safari","Bentley") For I=0 to 4 Response.write arrcar(i) & "<br>" Next %>
Dynamic array comes in handy (Versatile) when you aren’t sure how many items your array will hold. To create a dynamic array you should use the dim statement along with the array’s name, within specifying upper bound. <% dim arrcar arrcar=array() %> In order to use this array you need to use the ReDim statement to define the array’s upper bound:
Dim arrcar arrcar=Array() Redim arrcar(27) If in future you need to resize this array, you should use the redim statement again. Be very careful with the redim statement. When you use the redim statement you lose all the element of the array. Using the keyword PRESERVE in conjunction with the redim statement will keep the array we already have and increase the size.
<% Dim arrcar redim arrcar(3) arrcar=Array("Audi","Honda city","Mercedes","Safari","Bentley","lemo","alto") redim preserve arrcar(7) For i=0 to 6 Response.write arrcar(i) & "<br>" Next %>
Array don’t have to be a simple list of keys and values, each location in the array can hold another array. The reason you may use this type of array is when you have records of each item. For example car,year,price,…… and you want to display one record at a time. The most commonly used are two- dimensional arrays.You can thin of two dimensional array as a matrix, or grid , with width and height of rows and columns. Here is
how you could define two-dimensional array and display the array values on the web page. <% dim arrcar(2,4) arrcar(0,0)="honda city" arrcar(1,0)="2009" arrcar(2,0)="859598" arrcar(0,1)="audi" arrcar(1,1)="2009" arrcar(2,1)="450000"
dim a(1,1) a(0,0)="HTML" a(0,1)="Hyper Text Markup Language“ a(1,0)="ASP" a(1,1)="Active Server Page“ for i=0 to ubound(a,1) response.write("<table width=60% ><tr><td>") response.write(a(0,i)& "</td><td>") response.write(a(1,i)&"</td></tr>") next response.write("</table>")
Vb script is client side scriptlanguage and run on client side sowe do not require server and asp.It is lighter because no load atserver it completely run at clientside because all codes written inhtml.
Conversion of one data type to another is called type castingCintCdateAsc
ASC <% response.write("ANSI code of a string is: " & asc("a")) %> Cdate converts the date expression to the variant of subtype date <% a="march 14,1985" response.write ("<br>" & cdate(a)) %>
Cint Converts an expression to a variant of subtype Integer. <% Response.write(Cint(2314.166)) %>
Date <% response.write("current date of the system:“ & date) %> Time <% response.write(“Current time of the system" & time) %> Day <% response.write(“day of the system: " &day(date)) %>
WeekDayName <% response.write(“Name of the weekday :" & weekdayname(1)) %> WeekDay <% response.write("week day : " & weekday(date)) %> Month <% response.write("<br> month" &month(date)) %>
MonthName response.write(“Name of the month“ & monthname(3)) Year <% response.write("year:“ & year(date)) %>
1. Abs function The Abs function returns the absolute value of a specified number. Example <% Response.write (Abs(1) & “<br>”) Response.write(Abs(-1)) %>
Cos Function The cos function returns the cosine of a specified number. <% Response.write(cos(50.0)) %>
Exp Function The Exp function returns e raised to a power. <% Response.write(exp(6.7)) %> IntFunction The int function returns the integer part of a number <% Response.write(int(6.83227)) %>
Sqr Function The sqr function returns the square root of a number. <% Response.write(sqr(9)) %> Tan Function The tan function returns the tangent of a number< % Response.write(tan(59)) %>
The InStr function returns the positionof the first occurrence of one stringwithin another. <% dim a,b a="Have a Great Day Enjoy" b=instr(a,"Great") response.write(b) %> Output:8
The InStrRev function returns the positionof the first occurrence of one string withinanother. The search begins from the end ofstring, but the position returned counts fromthe beginning of the string <% dim a,b a="Have a Great Day Enjoy" b=instrrev(a,"Day") response.write(b) %> Output:14
The LCase function converts a specified string to lowercase.dim a a=“HAVE A GREAT DAY!"response.write(LCase(a))Output: have a great day!
The Left function returns a specifiednumber of characters from the leftside of a string. dim a a="This is a beautiful day!" response.write(Left(a,11)) Output:This is a b
The Len function returns the number ofcharacters in a string. dim a a="This is a beautiful day!" response.write(Len(a)) Output:24
The Mid function returns a specifiednumber of characters from a string. <% dim a a="Have a Great Day Enjoy" b=mid(a,8,9) response.write(b) %> Output: Great Day
The Replace function replaces a specified part of a string with another string a specified number of timesdim a a="This is a beautiful day!"response.write(Replace(a,"beautiful","horrible"))Output:This is a horrible day!
The String function returns a stringthat contains a repeating character of a specified length. response.write(String(10,"#")) Output:##########
An object is a thing or an entity like pen, table, chair, mobile phone, car etc. in other words, an object is a reusable component that contains related data and functions that represent some real-life things. A property is a basic characteristics of an object or you can say property is a value that describe the object, like color, shape etc. A method is something you can do with the object. In other words, method is a function which can be performed on the object. For example:1. Pen is used for writing.2. Chair is used for sitting.
Active Server Pages consist of six built in objects.They are ready made objects which providefunctionality to your web pages without requiringyou to make custom objects Following are the six built in ASP objects : 1. Application 2. ASP Error 3. Request 4. Response 5. Server 6. Session
A group of ASP files that worktogether to perform some purposeis called an application.
ASession object stores informationabout, or change settings for a usersession. Only store SMALL amountsof data in session variables!
The Response object is used to send the output back to the client (browser). It includes all the HTTP variables, cookies that will be stored on the client browser and other info about the content being sent
The Request object makes available all the values that client browser passes to the server during an HTTP request. It includes client browser info, cookie details ( of this domain only ), client certificates ( if accessing through SSL ) etc.
The ASPError object, implemented in ASP 3.0, contains detailed information about the last error that has occurred.
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. The Application object is used to store and access variables from any page, just like the Session object. The difference is that ALL users share ONE Application object (with Sessions there is ONE Session object for EACH user).
The Application object holds information that will be used by many pages in the application (like database connection information). The information can be accessed from any page. The information can also be changed in one place, and the changes will automatically be reflected on all pages.
Store and Retrieve Application VariablesApplication variables can be accessed and changed by any page in an application.You can create Application variables in "Global.asa"
Store and Retrieve Application VariablesApplication variables can be accessed and changedby any page in the application.You can create Application variables in "Global.asa"<script language="vbscript" runat="server">Sub Application_OnStart application(“cname")=“ infosys delhi "End Sub</script>
The Global.asa file can contain only the following:Application eventsSession events<object> declarationsType Library declarationsthe #include directiveNote: 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.
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. The Global.asa file can contain four types of events:
Application_OnStart - Occurs when the FIRST user calls the first page in an ASP application. This event occurs after the Web server is restarted or after the Global.asa file is edited. The "Session_OnStart" event occurs immediately after this event. Session_OnStart - This event occurs EVERY time a NEW user requests his or her first page in the ASP application.
Session_OnEnd - This event occurs EVERY time a user ends a session. A user-session ends after a page has not been requested by the user for a specified time (by default this is 20 minutes).Application_OnEnd - This event occurs after the LAST user has ended the session. Typically, this event occurs when a Web server stops. This procedure is used to clean up settings after the Application stops, like delete records or write information to text files.
<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>Because we cannot use the ASP script delimiters (<% and %>) to insert scripts in the Global.asa file, we put subroutines inside an HTML <script> element.
In this example we will create a Global.asa file that counts the number of current visitors.The Application_OnStart sets the Application variable "visitors" to 0 when the server startsThe Session_OnStart subroutine adds one to the variable "visitors" every time a new visitor arrives
The Session_OnEnd subroutine subtracts one from "visitors" each time this subroutine is triggeredThe Global.asa file:<script language="vbscript" runat="server"> Sub Application_OnStart Application("visitors")=0 End Sub
Sub Session_OnStart Application.Lock Application("visitors")=Application("visit ors")+1 Application.UnLock End Sub Sub Session_OnEnd Application.Lock Application("visitors")=Application("visit ors")-1 Application.UnLock End Sub </script>
To display the number of current visitors in an ASP file:<html> <head> </head> <body> <p>There are < %response.write(Application("visit ors"))%> online now!</p> </body> </html>
The ASP Server object is used to access propertiesand methods on the server. Its properties and methods are described below: Properties Script Timeout Sets or returns the maximum number of seconds a script can run before it is terminated Methods Create Object Creates an instance of an object Execute Executes an ASP file from inside another ASP file
GetLastError()Returns an ASP Error object that describes the errorcondition that occurredHTMLEncodeApplies HTML encoding to a specified string<%= Server.HTMLEncode("The paragraph tag: <P>") %>
MapPathMaps a specified path to a physical path<%=Server.MapPath(Request.ServerVariables("PATH_INFO"))%>TransferSends (transfers) all the information created in one ASP file to a second ASP fileURLEncodeApplies URL encoding rules to a specified string
ASession object stores informationabout, or change settings for a usersession. Only store SMALL amounts ofdata in session variables!
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.The computer knows who you are. It knows when you open the application and when you close it. 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.
A session starts when:A new user requests an ASP file, and the Global.asa file includes a Session_OnStart procedureA value is stored in a Session variableA user requests an ASP file, and the Global.asa file uses the <object> tag to instantiate an object with session scope
The most important thing about the Session object is that you can store variables in it.The example ahead will set the Session variable username to “Shawn" and the Session variable age to “30":
When the value is stored in a session variable it can be reached from ANY page in the ASP application:Welcome<%Response.Write(Session("username") )%>The line above returns: "Welcome Shawn".
The Contents collection contains all session variables.The example ahead removes the session variable "sale" if the value of the session variable "age" is lower than 18:
<% If Session.Contents("age")<18 then Session.Contents.Remove("sale") End If %>To remove all variables in a session, use the RemoveAll method:<% Session.Contents.RemoveAll() %>
PropertiesSessionID The SessionID is a read-only property that uniquelyidentifies each current users session. Each session hasa unique identifier that is generated by the server whenthe session is created and stored as a cookie on theclient machine.TimeOutThe Timeout property sets or returns the timeout period(in minutes) for thе Session object in this application. If the user does not refresh or request a page within the timeout period,the session ends. Can be changed inindividual pages as required.
Acookie is often used to identify auser.
Acookie is often used to identify auser. A cookie is a small file that theserver embeds on the userscomputer. Each time the samecomputer requests a page with abrowser, it will send the cookie too.With ASP, you can both create andretrieve cookie values.
The "Response.Cookies" command is used to create cookies.The Response.Cookies command must appear BEFORE the <html> tag.
IN THE EXAMPLE BELOW, WE WILLCREATE A COOKIE NAMED"FIRSTNAME" AND ASSIGN THEVALUE "ALEX" TO IT:<% Response.Cookies("firstname")="Alex" %>
IT IS ALSO POSSIBLE TO ASSIGNPROPERTIES TO A COOKIE, LIKESETTING A DATE WHEN THE COOKIESHOULD EXPIRE:<%Response.Cookies("firstname")="AlexResponse.Cookies("firstname").Expires =#May 10,2012# %>
The"Request.Cookies"command is used to retrieve acookie value
IN THE EXAMPLE BELOW, WERETRIEVE THE VALUE OF THE COOKIENAMED “FIRSTNAME" AND DISPLAY ITON A PAGE:<%fname=Request.Cookies("firstname")response.write("Firstname=" &fname)%>
Communication With User
Form Forms are a convenient way to communicate with visitors to your Web site. A form on a page allows a user to enter data that is sent to a server for processing
The <form> tag is used to create an HTML form for user input. A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain dropdown list, textarea elements. Forms are used to pass data to a server.
Attributes oF Form Action = Specifies where to send the form-data when a form is submitted Value =“url” Method = Specifies how to send form-data Value = “get or post” Name = Specifies the name for a form
Controls Users interact with forms through named controls. Each control has both an initial value and a current value, both of which are character strings.
Control types The Input Element The most important form element is the input element. The input element is used to select user information. An input element can vary in many ways, depending on the type attribute. An input element can be of type text field, checkbox, password, radio button, submit button, and more.
Attributes oFinput element
Text Fields <input type="text"> defines a one-line input field that a user can enter text into it. E.G. <form> First name: <input type="text" name="firstname"> Last name: <input type="text" name="lastname"> </form>
Radio Buttons <input type="radio"> defines a radio button. Radio buttons let a user select ONLY ONE one of a limited number of choices: E.G <form> <input type="radio" name="sex" value="male"> Male <input type="radio" name="sex" value="female"> Female </form>
Checkboxes <input type="checkbox"> defines a checkbox. Checkboxes let a user select ONE or MORE options of a limited number of choices. E.G. <form> <input type="checkbox" name="v1" value="Bike" /> I have a bike<br /> <input type="checkbox" name="v2" value="Car" /> I have a car </form>
Submit Button <input type="submit"> defines a submit button. A submit button is used to send form data to a server. The data is sent to the page specified in the forms action attribute. The file defined in the action attribute usually does something with the received input: <form name="input" action=“a.asp" method="get"> Username: <input type="text" name="user" /> <input type="submit" value="Submit" /> </form>
Pull down Lists: It is used to select one choice out of many choices. This control is very useful when we have number of choices and we have to choose only one particular choice. These lists occupy minimum amount of space. We use the <select> tag for this. Syntax <select name=”unique_name” size=”n”> <option value=”any_value”> <option value=”any_value ”> </select>
<html> <head><title>Asking for information</title></head> <body> <form method="post" action="form_response.asp"> Your name: <input type="text" name="name" size="20"><BR> Your email: <input type="password" name="email" size="15"><BR> <input type="Submit" value="Submit"> </form> </body> </html>
<html> <head><title>Responding to a form</title></head> <body> Your name is <% =Request.Form("name") %> <BR> Your email is <% =Request.Form("email") %> </body> </html>
The Response object is used to send the output backto the client (browser). It includes all the HTTPvariables, cookies that will be stored on the clientbrowser and other info about the content beingsent.
Redirect Redirects the browser to another page (URLe.g.Response.Redirect "http://www.gurchet.orgfree.com".Write Writes the specified string to the web page e.g. Response.Write "Hello World!".
The Request object makes available all the values that client browser passes to the server during an HTTP request. It includes client browser info, cookie details ( of this domain only ), client certificates ( if accessing through SSL ) etc.
Form Collection of all the values of Form element in the HTTP request.QueryString Collection of variables which are stored in the HTTP query string. Name / value pairs can also be appended to the URL after the end of page name e.g. "http://www.stardeveloper.com/asp_request.asp? author=Faisal+Khan" contains one variable author with a value of Faisal Khan.
Caching is a well known concept in computer science:when programs continually access the same set ofinstructions, a massive performance benefit can berealized by storing those instructions in RAM. This prevents the program from having to access thedisk thousands or even millions of times during execution by quickly retrieving them from RAM. Caching on the web is similar in that it avoids a roundtrip to the originweb server each time a resource is requested andinstead retrieves the file from a local computers browsercache or a proxy cache closer to the user.
The Buffer property specifies whether to bufferthe output or not. When the output is buffered, theserver will hold back the response to the browseruntil all of the server scripts have beenprocessed, or until the script calls the Flush orEnd method.Note: If this property is set, it should be beforethe <html> tag in the .asp file response.Buffer[=flag]
For Communicating With User We Use Forms In Form We Have Two Method For Communicating User1. Method Post2. Method GetForm tag provide various form fields for sending information to server. And we use these fields to communicating. Like text field to send mails
Another <form> tag attribute specifies how theinformation will be sent to wherever its going. Thats the"method" attribute. The method attribute is eithermethod="POST"ormethod="GET"Which you use depends on how the destination programor function wants to receive the information.
Sending With Method GET method="GET" is used if you want to send information somewhere via a browser URL. Youve seen URLs that send information; they look something like:http://gurchet.orgfree.com/handler.name? color=red&shape=round In the above URL, the part after the question mark is information sent to handler.name. Multiple information chunks are separated with an ampersand. The GET method can send only a limited amount of information. The limitation depends on the server where the current web page is on and the server where the information is sent to. The limitation can be as little as 256 bytes but is often 1k or more.
Accessing the HTTP HeadersStandard HTTP HeadersEnvironment Variables Using CookiesAdvantages & disadvantages cookies
When the client request a web page from the server it not only sends the url of web page requested but also send some additional information this extra information consists of useful facts about the client1. What browser is being used2. What operating system the client running3. What url the user just come fromThese information are called request header
Request Header is a single line of text that yourbrowser sends to the web Server when requesting toview any web page.Response Header when the server sends back therequested web page to the client it also sends a setof headers known as response headers.Both request headers and response headers arecalled HTTP Header
An HTTP Header is a single piece of informationsent either from client To the server whenrequesting a page or from the server to the clientwhen Responding to a page request. 1. HTTP_ACCEPT 2. HTTP_ACCEPT_LANGAGUE 3. HTTP_CONNECTION 4. HTTP_HOST 5. HTTP_USER_AGENT 6. HTTP_REFERER 7. HTTP_COOKIE
The HTTP Headers are useful for obtaining information about current Visitor but tell you nothing about the web server or asp page that is being requested by the client. To obtain such information we use web server’s Environment Variables Environment Variables are bit of information that web browser make available to any Program that requested them. It contain information such as:-1. Name of web server2. url currently processing asp page3. Name of software being used by web server.
1. URL 2. PATH_INFO 3. PATH_TRANSLATED 4. APPL_PHYSICAL_PATH 5. QUERY_STRING 6. SERVER_NAME 7. SERVER_SOFTWAREMany environment variables do not contain a value because it use whenrequired for example CERT Variable contains empty strings as their value.This is because these variable are Used only when client and server useCERTIFICATES .When a browser and web Server communicate over asecure channel, certificates are used to ensure the identity of the Client tothe server.
Cookies are small amount of information stored in clientcomputer for some time.When cookies are created on the client computer the developerneed to specify when they expire. After a cookie expire it willautomatically remove itself from the client computer.Cookies created response.cookies(“user”)=“John”Cookies read request.cookies(“user”)Cookies expire response.cookies(“user”).expires=date+10
1. Cookies stores on client computer so not need more space in web server2. Save small amounts of information for very long periods of time3. It is used to customize a user visit to your web site1. User can choose not to accept cookies on their web browser2. It not save large amount to date3. It save only string, date or numeric date4. It is not secure because if temp folder deleted it also delete all cookies
1. Web is stateless ?2. Why to maintain state ?3. Session Object4. Asp application object5. Asp global.asa file6. Events in global.asa
An application is said to have state if it persists information for each user. In a web site this is notthe case for example if you fill out s form on A webpage and then revisit the form at some time laterthe form fields will not contain The valued you enteredearlier because web site lack state this is calledstateless
For maintaining state asp provides many waysthese ways are used to kept informationWhich is used in round tripping process.In asp we have build in objects and collection formaintaining stateSession object and application objects are used forthis purpose,cookies are also used to Maintain state
PITFALLS OF SESSION VARIABLES (DRAWBACKS)If user select that his system not save session then session not workDefault time is 20 minute it is also big disadvantages
The ASPError object, implemented in ASP 3.0, contains detailed informationabout the last error that has occurred.This information can only be accessed through the Server.GetLastError.The ASPError object has nine read-only properties and no methods.Properties•ASP CodeThis property returns the error code generated by IIS.•DescriptionThe description property returns the short description of the error.•ASP DescriptionReturns a string that contains more detailed error information than the Description property, but it is not available for all errors.
There are 3 main types of errors:Compile-time errorsThese errors are usually in the syntaxof the code and stop the ASP fromcompiling. You may have experienced this if you left the closing ”Next”statement off of a “For” loop.
Runtime errorsThese happen when you try to execute the ASP page. For example, if you trysetting a variable outside its allowed range.Logic errorsLogic errors are harder to detect.The problem lies within the structure ofthe code, and the computer cannot detectan error. These types require thoroughtesting before rolling out the application.
5- invalid procedure call6- overflow7- out of memory11- division by zero13- type mismatch53- internal error61- disk full76- path not found438- object not support method or property424- object required
<% On Error Resume Next X = 15 Y=5 Z = 15Response.Writes( X/Y & "<b><br>")Response.Write( X/Z & "<b><br>") If Err.Number = 0 Then response.write("no error") else Response.Write(err.number & "<br>") Response.Write(err.description) End If%>
Non Asp ErrorError Created By Server Is Called Non Asp ErrorIn This type Of Error Program Is Not ExecutatedBecause Server Creates Problem.Some Time Message Come – Server Not Exist OrFile Not Found
database:A collection of related information storedin a structured format.Database is often used interchangeablywith the term tableA table is a single store of relatedinformation; a database can consist ofone or more tables of information that arerelated in some way.
data entry: The process of getting information into adatabase, usually done by people typingit in by way of data-entry forms designed to simplify the process.
dbms: Database management system.A program which lets you manage information in databases.Lotus Approach, Microsoft Access andFileMaker Pro, for example, are all DBMSs,although the term is often shortened todatabase. So, the same term is used toapply to the program you use toorganise your data and the actualdata structure you create with that program.
field:Fields describe a single aspect ofeach member of a table.A student record, for instance, mightcontain a last name field, a first name field,a date of birth field and so on. All recordshave exactly the same structure, so theycontain the same fields. The values in eachfield vary from record to record, of course.In some database systems, youll find fieldsreferred to as attributes.
flat file:A database that consists of a single table. Lightweight database programs such asthe database component in Microsoft Worksare sometimes called flat-file managers‘ (or list managers) because they can onlyhandle single-table databases. More powerful programs, such as FileMaker Pro, Access,Approach and Paradox, can handlemulti-table databases, and arecalled relational database managers,or RDBMSs.
primary key: A field that uniquely identifies a record ina table. In a students table, for instance,a key built from last name + first namemight not give you a unique identifier (two or more Jane Does in the school,for example). To uniquely identify eachstudent, you might add a special StudentID field to be used as the primary key.
foreign key:A key used in one table to represent thevalue of a primary key in a related table.While primary keys must contain uniquevalues, foreign keys may have duplicates.For instance, if we use student ID as theprimary key in a Students table(each student has a unique ID),we could use student ID as a foreign keyin a Courses table: as each student maydo more than one course,
index:A summary table which lets you quickly lookup the contents of any record in a table.Think of how you use an index to a book:as a quick jumping off point to finding full information about a subject. A databaseindex works in a similar way. You can create an index on any field in a table
SQL: Structured Query Language (pronounced sequelin the US; ess-queue-ell elsewhere). A computer language designed to organizeand simplify the process of getting informationout of a database in a usable form, and alsoused to reorganize data within databases.SQL is most often used on larger databaseson minicomputers, mainframes andcorporate servers.
query:A view of your data showing informationfrom one or more tables. For instance,using the sample database we used whendescribing normalisation, you could querythe Students database asking "Show me thefirst and last names of the studentsWhose roll no is 90821.
RDBMS: Relational database managementsystem.A program which lets you managestructured informationstored in tables and which canhandle databasesconsisting of multiple tables.
RECORD:A record contains all the informationabout a single member of a table. In astudents table, each students details(name, date of birth, contact details,and so on) will be contained in its ownrecord.
RELATIONAL DATABASE:A database consisting of more thanone table. In a multi-table database,you not only need to define the structureof each table, you also need to definethe relationships between each tablein order to link those tables correctly.
REPORT:A form designed to print information from adatabase (either on the screen, to a file ordirectly to the printer).
TABLE: A single store of related information. A table consists of records, and eachrecord is made up of a number of fields.Just to totally confuse things, tables are sometimes called relations. You can thinkof the phone book as a table: It contains a record for each telephone subscriber, and each subscribers details are containedin three fields - name, address and telephone.
Dr. E.F. Codd, an IBM researcher,first developed the relational data model in 1970.In 1985, Dr. Codd published a list of 12 rules that concisely define an ideal relational database,which have provided a guideline for the design of all relational database systems ever since.
Rule 1: The Information Rule All data should be presented to the user in table formRule 2: Guaranteed Access RuleAll data should be accessible withoutAmbiguity (doubt). This can be accomplishedthrough a combination of the table name,primary key, and column name.
Rule 3:Systematic Treatment of Null ValuesA field should be allowed to remain empty. This involves the support of a null value, which is distinct from an empty stringor a number with a value of zero. Of course, this cant apply to primary keys. In addition, most database implementations support the concept of a nun- null field constraint thatprevents null values in a specific table column.
Rule 4:Dynamic On-Line Catalog Based on theRelational ModelA relational database must provide access to its structure through the same tools that are used to access the data. This is usuallyaccomplished by storing the structure definition within special system tables.
Rule 5:Comprehensive Data Sublanguage RuleThe database must support at least one clearly defined language that includesfunctionality for data definition, datamanipulation, data integrity, and databasetransaction control. All commercialrelational databases use forms of thestandard SQL (Structured Query Language)as their supported comprehensive language.
Rule 6: View Updating RuleData can be presented to the user in different logical combinations, called views. Eachview should support the same full rangeof data manipulation that direct-access to a table has available. In practice, providing update and delete access to logical views is difficult and is not fully supported by any current database.
Rule 7:High-level Insert, Update, and DeleteData can be retrieved from a relationaldatabase in sets constructed of datafrom multiple rows and/or multiple tables.This rule states that insert, update, and delete operations should be supported for anyretrievable set rather than just for a singlerow in a single table
Rule 8: Physical Data IndependenceThe user is isolated from the physicalmethod of storing and retrieving informationfrom the database. Changes can be madeto the underlying architecture( hardware, disk storage methods )without affecting how the user accesses it.
Rule 9: Logical Data IndependenceHow a user views data should not changewhen the logical structure (tables structure)of the database changes. This rule is particularly difficult to satisfy. Most databases rely on strong ties between the user view of the data and theactual structure of the underlying tables.
Rule 10: Integrity IndependenceThe database language (like SQL)should support constraints on user inputthat maintain database integrity. Thisrule is not fully implemented by mostmajor vendors. At a minimum, alldatabases do preserve two constraintsthrough SQL.No component of a primary key canhave a null value. (see rule 3)If a foreign key is defined in one table, any value in it must exist as a primary key in another table.
Rule 11: Distribution IndependenceA user should be totally unaware of whetheror not the database is distributed (whether partsof the database exist in multiple locations). A variety of reasons make this rule difficult to implement;
Rule 12: Nonsubversion RuleThere should be no way to modify thedatabase structure other than through themultiple row database language (like SQL).Most databases today support administrativetools that allow some direct manipulation ofthe datastructure.
1.What is ADO?ADO is a Microsoft technologyADO stands for ActiveX Data ObjectsADO is a Microsoft Active-X componentADO is automatically installed withMicrosoft IISADO is a programming interface to accessdata in a database
2.Accessing a Database from an ASP PageThe common way to access a database frominside an ASP page is to:Create an ADO connection to a databaseOpen the database connectionCreate an ADO recordsetOpen the recordsetExtract the data you need from the recordsetClose the recordsetClose the connection
3. How DSN-less Database Connection Created ?The easiest way to connect to a database is to use a DSN-less connection. A DSN-less connection can beused against any Microsoft Access database on yourweb site.If you have a database called "northwind.mdb" located in a web directory like "c:/webdata/",you can connect to the database with the followingASP code:<% set conn=Server.CreateObject("ADODB.Connection")conn.Provider="Microsoft.Jet.OLEDB.4.0“conn.Open "c:/webdata/northwind.mdb"%>
4. What is Connection Object ?The ADO Connection Object is used to createan open connection to a data source. Throughthis connection,you can access and manipulatea database.If you want to access a databasemultiple times,you should establish aconnection using the Connection object. Youcan also make a connection to a database bypassing a connection string via a Command orRecordset object. However,this type ofconnection is only good for one specific, singlequery.set objConnection=Server.CreateObject("ADODB.connection")
5. What is Recordset Object ?The ADO Recordset object is used to hold a set of records from a database table. A Recordset object consist ofrecords and columns (fields).In ADO, this object is the most important and the oneused most often to manipulate data from a database.set objRecordset=Server.CreateObject("ADODB.recordset")
7. How Data is Extracted from Record set After a record set is opened, we can extract data from record set. Suppose we have a database named "North wind", we can get access to the "Customers" table inside the database<%dim conset con=Server.createObject("ADODB.connection")con.open "provider=microsoft.jet.oledb.4.0;Data source="& server.mappath("db1.mdb")set rs=Server.createObject("ADODB.Recordset")q="select * from stu"rs.open q,conresponse.write("<table border=3 align=center height=30% width=20% >"&"<tr><th>")response.write("ID" & "</td><td>" & "<b> Name"& "</td><td>" & "<b>Marks")
response.write("</td></tr>")response.write("<br>")do while not rs.EOFresponse.write("<tr><td>")response.write(rs("id")&" " & "</td><td>")response.write(rs("name")&" " & "</td><td>")response.write(rs("marks")&" " & "</td>")response.write("<br>")response.write("</tr>")rs.movenextloop%>
Recordset Object The ADO Recordset object is used to hold a set of records from a database table. A Recordset object consist of records and columns (fields). In ADO, this object is the most important and the one used most often to manipulate data from a database.
What is Recordset updating:Immediate updating - all changes arewritten immediately to the database once you call the Update method.Batch updating - the provider will cachemultiple changes and then send themto the database with the UpdateBatch method.
12. Define 4 different types of cursor in ADOCursor:Database cursor is a control structure that enables traversalover the records in a database. Cursors are used by databaseprogrammers to process individual rows returned by databasesystem queries.Types Of CursorDynamic cursor –Allows you to see additions, changes,and deletions by other users.Keyset cursor – Like a dynamic cursor, except that you cannotsee additions by other users, and it prevents accessto records that other users have deleted.
Static cursorProvides a static copy of a recordset for you touse to find data or generate reports. Static cursorsSupport scrolling backward and forward, but theydo not support updates.This is the only type of cursorallowed when you open a client-side Recordset object.The following is an example of how to obtain a staticcursor by using ADO.NET:cmd.CommandText = "Select * from tablename";SqlCeResultSet rs = cmd.ExecuteResultSet(ResultSetOptions.Scrollable | ResultSetOptions.Insensitive);
Forward-only cursor-Allows you to only scroll forward through theRecordset.-Additions, changes, or deletions by other users willnot be visible.Popular Relational Database ProductSQL 7ORACLE8SYSBASEIBM’S DB2INFORMIX