22
CVEV 118/698 CVEV 118/698 Active Server Active Server Pages Pages Lecture 3 Lecture 3 Prof. Mounir Mabsout Prof. Mounir Mabsout Elsa Sulukdjian Elsa Sulukdjian Walid El Asmar Walid El Asmar

CVEV 118/698 Active Server Pages Lecture 3 Prof. Mounir Mabsout Elsa Sulukdjian Walid El Asmar

  • View
    215

  • Download
    0

Embed Size (px)

Citation preview

CVEV 118/698CVEV 118/698 Active Server Active Server

PagesPagesLecture 3Lecture 3

Prof. Mounir MabsoutProf. Mounir MabsoutElsa SulukdjianElsa SulukdjianWalid El AsmarWalid El Asmar

What is ASP?What is ASP? ASP stands for Active Server Pages. ASP stands for Active Server Pages. It is a server side technology which is used It is a server side technology which is used

to display dynamic content on web pages. to display dynamic content on web pages. For example you could write code that For example you could write code that

would give you different information would give you different information depending on what browser version you are depending on what browser version you are using.using.

ASPASP in itself isn't a language it is more in itself isn't a language it is more a technology developed by Microsoft. a technology developed by Microsoft.

ASPASP can be used with various scripting can be used with various scripting languages such as languages such as Vbscript, PerlVbscript, Perl or or Jscript.Jscript.

What Can You Do with What Can You Do with ASP?ASP?

There are many things you can do with There are many things you can do with ASPASP: : – You can easily access databases and present the You can easily access databases and present the

results on your web site. results on your web site. – You can easily update, edit or delete content on a You can easily update, edit or delete content on a

page.page. – You can create login and password protected sites.You can create login and password protected sites.– You can create customized pages that display only You can create customized pages that display only

things that will be of interest to a particular user, things that will be of interest to a particular user, display different pages for different browsers, etc.display different pages for different browsers, etc.

– You can have pictures that display randomly.You can have pictures that display randomly.– You can display the date, time and other You can display the date, time and other

information in various different formats.information in various different formats.– You can make a survey form and ask people who You can make a survey form and ask people who

visit your site to fill it out, send emails, save the visit your site to fill it out, send emails, save the information to a file, etc.information to a file, etc.

Server-Side TechnologyServer-Side Technology ASP is run server-side.ASP is run server-side. When you request a page with the extensionWhen you request a page with the extension .ASP: .ASP:

– thethe web server looks and locates the page web server looks and locates the page – then it executes the then it executes the ASPASP script contained in the page and script contained in the page and – sends back to your browser a sends back to your browser a pure htmlpure html page. page.

The server can be a computer on the internet, or on The server can be a computer on the internet, or on a local intranet. a local intranet.

This ensures that an This ensures that an ASPASP page will work with any page will work with any browser. browser.

This is what is meant when by This is what is meant when by server side server side technology:technology:All the ASP code is processed first of all on the All the ASP code is processed first of all on the server before being sent back to be displayed by server before being sent back to be displayed by your browser.your browser.

HTML Page DisplayHTML Page Display

ASP Page DisplayASP Page Display

Note:Note: ASPASP pages end with the file extension pages end with the file extension .asp.asp as opposed as opposed to to htmlhtml files that have the files that have the .html.html extension. extension.

Server-Side ScriptsServer-Side Scripts Server-side scripts look a lot like HTML Server-side scripts look a lot like HTML

tags. tags. However, instead of starting and ending However, instead of starting and ending

with lesser-than ( with lesser-than ( << ) and greater-than ( ) and greater-than ( >> ) ) brackets, they typically start with brackets, they typically start with <%<% and and end with end with %>%>. .

The The <% <% is called an is called an opening tagopening tag, and the , and the %>%> is called a is called a closing tagclosing tag. In between . In between these tags are the these tags are the Server-Side ScriptsServer-Side Scripts. .

You can insert server-side scripts anywhere You can insert server-side scripts anywhere in your Web page - even inside HTML tags. in your Web page - even inside HTML tags.

What It Looks LikeWhat It Looks Like Your ASP page will invariably be a mixture Your ASP page will invariably be a mixture

of text, ASP, and html tags. of text, ASP, and html tags. Example: In yellow is the html. In red is the Example: In yellow is the html. In red is the

text and in white is the ASP (Vbscript).text and in white is the ASP (Vbscript).<html><html><head><head><title>Mixture</title><title>Mixture</title></head></head>

<body><body> The time currently isThe time currently is <%= Time %><%= Time %> <br><br><font size="4" font color="red"><font size="4" font color="red">and the date and the date isis</font></font><%= Date%><%= Date%></body></body></html></html>

CommentsComments Just to point out that using an apostrophe at the Just to point out that using an apostrophe at the

start of a line or anywhere in a line of ASP code start of a line or anywhere in a line of ASP code comments out that code. It will not be processed.comments out that code. It will not be processed.<%<%‘This is a comment‘This is a commentresponse.write “Hello” ‘This also is a commentresponse.write “Hello” ‘This also is a comment%>%>

It is advisable that you clearly comment your It is advisable that you clearly comment your code.code.

To print out code use To print out code use <%=<%=  or  or response.writeresponse.write. . <%= “Hello” %> <%= “Hello” %> oror<% response.write “Hello” %><% response.write “Hello” %>

Note:Note: delimiters don’t have to be on the same delimiters don’t have to be on the same line of code.line of code.

ASP Primary LanguageASP Primary Language

VBScriptVBScript is the default language for is the default language for ASP scripts. ASP scripts.

If you are using something other than If you are using something other than VBScriptVBScript, you must specify the , you must specify the language; at the top of the page, add language; at the top of the page, add this line: this line:

<%@LANGUAGE=ScriptingLanguage%><%@LANGUAGE=ScriptingLanguage%>

VBScript & VariablesVBScript & Variables In In VBScriptVBScript, you don't have to declare variables or , you don't have to declare variables or

explicitly define their type (they are variant by explicitly define their type (they are variant by default). default).

A variable exists the first time you use it. A variable exists the first time you use it. However, if you mistype a variable name somewhere However, if you mistype a variable name somewhere

in the code, a new variable is created. Your script may in the code, a new variable is created. Your script may not work properly, and you may not even realize it. not work properly, and you may not even realize it.

So better declare variables before using them:So better declare variables before using them:<%Dim IntVar%><%Dim IntVar%>

Moreover,Moreover, i if you turn on f you turn on Option ExplicitOption Explicit, you'll get , you'll get an error any time you use a variable that has not been an error any time you use a variable that has not been defined:defined:

<% Option Explicit %><% Option Explicit %>

String ManipulationString Manipulation InStr(StrBeingSearched, StrSearchingFor)InStr(StrBeingSearched, StrSearchingFor)

returns the position at which the string being search returns the position at which the string being search for was located.for was located.

Left(StrToPullFrom, NumofCharactersToPull)Left(StrToPullFrom, NumofCharactersToPull) returns the numbers of characters you state starting returns the numbers of characters you state starting from the left. Same for from the left. Same for Right()Right()..

Len(StrToCheck)Len(StrToCheck) returns the length of the string.returns the length of the string.

LCase()LCase() and and UCase()UCase()to pass in the string variable and to pass in the string variable and convert the string into either uppercase or lowercase.convert the string into either uppercase or lowercase.

Trim(strName)Trim(strName) returns returns strName strName without white without white spaces on its left or right side. To trim the right/left spaces on its left or right side. To trim the right/left side, use Rtrim (strName) or Ltrim(strName).side, use Rtrim (strName) or Ltrim(strName).

If… Then… Else… End IfIf… Then… Else… End If<% @ Language="VBScript" %><% @ Language="VBScript" %><% Option Explicit %> <% Option Explicit %> <html><html><head><title>Exam marks</title></head><head><title>Exam marks</title></head><body><body><%<%Dim Grade      'comment - variable declarationDim Grade      'comment - variable declarationGrade=45       'variable holds the value 45Grade=45       'variable holds the value 45%>%><% <% If Grade>=70 Then If Grade>=70 Then response.write "You have a good grade" response.write "You have a good grade"Else If Grade >=50 AND Grade <70 Then Else If Grade >=50 AND Grade <70 Then response.write "You have an average grade" response.write "You have an average grade"ElseElse response.write "You failed" response.write "You failed"End If End If %>%></body> </body> </html> </html>

Select CaseSelect Case Select Case is quite similar to the If..Then..Else...Select Case is quite similar to the If..Then..Else...

<%<%SELECT CASE NumberSELECT CASE NumberCase 1Case 1Response.write “Number is equal to 1”Response.write “Number is equal to 1”……Case ElseCase ElseResponse.write "The number is not equal to any of the values above "Response.write "The number is not equal to any of the values above "END SELECT END SELECT %> %>

Same applies to strings:Same applies to strings:<%<%SELECT CASE NameSELECT CASE NameCase “String”Case “String”……

Note:Note: with SELECT CASE you cannot use < and >. with SELECT CASE you cannot use < and >.

LoopsLoops Do While… LoopDo While… Loop

<%<% i = 0 i = 0 Do While i < 10     Do While i < 10    

response.write("Hello<HR>") response.write("Hello<HR>") i = i + 1 i = i + 1

Loop %>Loop %>

Do Until… LoopDo Until… Loop<% i = 0 <% i = 0

Do Until i =10     Do Until i =10     response.write("Hello<BR>") response.write("Hello<BR>") i = i +1 i = i +1

Loop %>Loop %>

For… Next LoopFor… Next Loop<% For i = 1 to 20 STEP 2 <% For i = 1 to 20 STEP 2 response.write("Hello<BR>") response.write("Hello<BR>") Next %>Next %>

ArraysArrays Create an array (arrays in ASP have a zero based Create an array (arrays in ASP have a zero based

index):index):– Dim strArray(2) Dim strArray(2) ‘strArray contains 3 elements‘strArray contains 3 elements– Dim strArray = Array (“a”,”b”,”c”)Dim strArray = Array (“a”,”b”,”c”)

Enlarge an array:Enlarge an array:– ReDim Preserve strArray(3) ReDim Preserve strArray(3) ‘Contains 4 elements‘Contains 4 elements

Split an array:Split an array:Split(StrToSplit[, DelimiterToUse, HowMany])Split(StrToSplit[, DelimiterToUse, HowMany])– Returns a one dimensional arrayReturns a one dimensional array– DelimiterToUse and HowMany are optional parameters.DelimiterToUse and HowMany are optional parameters.– If you leave out the DelimterToUse, the function uses a If you leave out the DelimterToUse, the function uses a

space to split the string.space to split the string. Multi-Dimensional arrays, ArrayName (col, row):Multi-Dimensional arrays, ArrayName (col, row):

– Dim strArray(2,3) Dim strArray(2,3) ‘strArray contains 3 * 4 elements‘strArray contains 3 * 4 elements

Error HandlingError Handling A good way to deal with an error is to use A good way to deal with an error is to use On Error On Error

Resume NextResume Next.. This tells the server to resume the next line of code This tells the server to resume the next line of code

if it encounters an error. if it encounters an error. On Error Resume NextOn Error Resume Next is usually placed at the top is usually placed at the top

of each page. of each page. Example:Example:

<%<%On Error Resume NextOn Error Resume Nextresponse.write (“There is an error here!") response.write (“There is an error here!")

If Err.number <> 0 then If Err.number <> 0 then response.write Err.description response.write Err.description End If End If %>%>

Connecting to a Connecting to a DatabaseDatabase

First instantiate the Connection Object:First instantiate the Connection Object:Set Connection = Server.CreateObject("ADODB.Connection")Set Connection = Server.CreateObject("ADODB.Connection")

Next define the actual connection string:Next define the actual connection string:sConnString = "DRIVER={Microsoft Access Driver (*.mdb)};" & _ sConnString = "DRIVER={Microsoft Access Driver (*.mdb)};" & _ "DBQ=" & Server.MapPath("databasename.mdb") & ";""DBQ=" & Server.MapPath("databasename.mdb") & ";"

Note: Note: This statement tells the ADO (Active Data Objects) This statement tells the ADO (Active Data Objects) that we want to use the MS Access driver where our that we want to use the MS Access driver where our database is physically located. The database is physically located. The databasename.mdbdatabasename.mdb will be in the same folder as your asp page.will be in the same folder as your asp page.

Open the connection to the database. Open the connection to the database. Connection.Open(sConnString)Connection.Open(sConnString)

Execute a SQL statement:Execute a SQL statement:sql = "SELECT * FROM myTable"sql = "SELECT * FROM myTable"Set Recordset = Connection.Execute(sql)Set Recordset = Connection.Execute(sql)

ExampleExample<%<% ‘declare your variables‘declare your variablesDim Connection, sConnString,sql,recordsetDim Connection, sConnString,sql,recordsetSet Connection = Server.CreateObject("ADODB.Connection")Set Connection = Server.CreateObject("ADODB.Connection")sConnString = "DRIVER={Microsoft Access Driver (*.mdb)};" & _ "DBQ=" & sConnString = "DRIVER={Microsoft Access Driver (*.mdb)};" & _ "DBQ=" &

Server.MapPath("databasename.mdb") & ";"Server.MapPath("databasename.mdb") & ";"Connection.Open(sConnString)Connection.Open(sConnString)sql = "SELECT * FROM myTable"sql = "SELECT * FROM myTable"Set Recordset = Connection.Execute(sql) Set Recordset = Connection.Execute(sql)

‘Check if there are any records in the recordset‘Check if there are any records in the recordsetIf not Recordset.eof ThenIf not Recordset.eof Then

response.write "There are records"response.write "There are records"ElseElse

response.write "There are no records"response.write "There are no records"End ifEnd if

Recordset.CloseRecordset.CloseSet Recordset = NothingSet Recordset = NothingConnection.CloseConnection.CloseSet Connection = NothingSet Connection = Nothing %>%>

Inserting Data in a DB Inserting Data in a DB TableTable

The code below inserts data into the table The code below inserts data into the table "Friends". "Friends". <%<%myDSN=“DSN = DataSourceName"myDSN=“DSN = DataSourceName"SQL=“INSERT INTO Friends (FirstName, LastName) “ & _ SQL=“INSERT INTO Friends (FirstName, LastName) “ & _ “VALUES (‘Walid', ‘Asmar’)”“VALUES (‘Walid', ‘Asmar’)”Set Connection = Server.CreateObject("ADODB.Connection")Set Connection = Server.CreateObject("ADODB.Connection")Connection.Open(myDSN)Connection.Open(myDSN)Connection.Execute(SQL)Connection.Execute(SQL)Connection.CloseConnection.CloseSet Connection = NothingSet Connection = Nothing%>%>

Displaying Records from Displaying Records from a Tablea Table

<%<%

……

If Rst.EOF and Rst.BOF ThenIf Rst.EOF and Rst.BOF Then

Response.Write("No records returned.")Response.Write("No records returned.")

ElseElse

Do While Not Rst.EOFDo While Not Rst.EOF

Response.Write(Rst("Firstname")&" - "&Rst("Lastname"))Response.Write(Rst("Firstname")&" - "&Rst("Lastname"))

Rst.MoveNextRst.MoveNext

LoopLoop

End IfEnd If

……

%>%>

What’s Next ?What’s Next ?

Nothing! Nothing!