450 likes | 671 Views
Matakuliah : T0053/Web Programming Tahun : 2006 Versi : 2. Pertemuan 3 Server Side Scripting (ASP & ASP .Net). Learning Outcomes. Pada akhir pertemuan ini, diharapkan mahasiswa akan mampu : Menjelaskan konsep server side scripting Membuat program menggunakan ASP & ASP .Net.
E N D
Matakuliah : T0053/Web Programming Tahun : 2006 Versi : 2 Pertemuan 3Server Side Scripting(ASP & ASP .Net)
Learning Outcomes Pada akhir pertemuan ini, diharapkan mahasiswa akan mampu : • Menjelaskan konsep server side scripting • Membuat program menggunakan ASP & ASP .Net
Material Outline • Mengenal Server side scripting • Pemrograman dasar ASP & ASP .Net • Koneksi ke database
Server Side Scripting • Server Side Scripting is script that execute in web server (IIS, Apache Web Server, etc) • Server Side Scripting very useful if require validation against database, server processing and security.
Introduction to ASP • ASP (Active Server Pages) is server side scripting from Microsoft that usually uses Internet Information Services (IIS) as web server. • Active Server Pages (ASP) • Processed in response to client request • ASP file contains HTML and scripting code • VBScript de facto language for ASP scripting • Other languages can be used • JavaScript • .asp file extension • Microsoft-developed technology • Send dynamic Web content • HTML • DHTML • ActiveX controls • Client-side scripts • Java applets
How ASP Work • Client sends request • Server receives request and directs it to ASP • ASP processes, then returns result to client • HTTP request types • Request methods • GET • Gets (retrieves) information from server • Retrieve HTML document or image • POST • Posts (sends) data to server • Send info from HTML form • Client-entered data • Info to search Internet • Query for a database • Authentication info
How ASP Work • Browsers often cache Web pages • Cache: save on disk • Typically do not cache POST response • Next POST request may not return same result • Client requests ASP file • Parsed (top to bottom) by ActiveX component asp.dll • ActiveX component: server-side ActiveX control that usually does not have GUI • Code executed as encountered • @LANGUAGE statement • Specifies scripting language • If not used, VBScript assumed • As interpreted, HTML (plus client-side scripts) sent to client • Parsed each time requested • Web server must support ASP by providing component such as asp.dll
Client Side VS Server Side • Client-side scripting • Used for: • Validation • Interactivity • Enhancing Web page with ActiveX controls • Dynamic HTML • Java applets • Accessing browser • Browser-dependent • Scripting language must be supported by browser or scripting host • Viewable on client • Protecting source code difficult
Client Side Vs Server Side • Server-side scripting • Reside on server more flexibility • Database access • Usually generate custom response for client • Access to ActiveX server components • Extend scripting language functionality • Run exclusively on server cross-platform issues not a concern • Not visible to client • Only HTML + client-side scripts sent to client
ASP Example • Scripting delimiters • <% and %> • Indicate code is to be executed on server, not client • @LANGUAGE • Specify scripting language (default VBScript) • <% @LANGUAGE = “VBScript” %> • Each time page refreshed, server loads and interprets ASP
1<% @LANGUAGE = VBScript %> 2<%Option Explicit%> 3<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 4<%' Fig. 26.1 : clock.asp%> 5 6<HTML> 7<HEAD> 8<TITLE>A Simple ASP Example</TITLE> 9<META HTTP-EQUIV ="REFRESH"CONTENT = "60; URL = CLOCK.ASP"> 10</HEAD> 11<BODY> 12 13<FONT FACE =ARIALSIZE =4><STRONG>Simple ASP Example</STRONG> 14</FONT><P> 15<TABLE BORDER ="6"> 16 <TR> 17<TD BGCOLOR ="#000000"> 18 <FONT FACE =ArialCOLOR ="#00FF00"SIZE =4> 19<% =Time() %> 20 </FONT> 21 </TD> 22 </TR> 23 </TABLE> 24</BODY> 25</HTML> 1.1 Specify VBScript as scripting language 1.2 Use Option Explicit to indicate variables be explicitly declared by programmer 1.3 Use META tag to set refresh interval Time gets current time on server (hh:mm:ss) Short for <% Call Response.Write( Time() ) %>
Server Side ActiveX Component • Server-side ActiveX components • Typically do not have GUI • If scripting language for ASP not support certain feature, create ActiveX Server component • Visual C++, Visual Basic, Delphi, etc. • Usually execute faster than scripting language equivalents • Executed on server • Client does not need to support ActiveX technologies
Some server-side ActiveX components included with IIS and PWS
1<% @LANGUAGE = VBScript %> 2<%Option Explicit%> 3<%' Fig. 26.3 : rotate.asp%> 4 5<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 6<HTML> 7<HEAD> 8<TITLE>AdRotator Example</TITLE> 9</HEAD> 10 11<BODY> 12<FONT FACE = "Arial" SIZE = 4><STRONG>AdRotator Example</STRONG> 13</FONT><P> 14<% 15 ' Declare flagChanger 16Dim flagChanger 17 18 ' Create an AdRotator object 19Set flagChanger = Server.CreateObject( "MSWC.AdRotator" ) 20 21 ' Use config.txt to send an advertisement to the client 22Call Response.Write( _ 23 flagChanger.GetAdvertisement( "config.txt" ) ) 24%> 25</BODY> 26</HTML> 1.1 Create instance of AdRotator component 1.2 Call Response object’s Write method to send advertisement to client
27 WIDTH 54 28 HEIGHT 36 29 BORDER 1 30 * 31 /images/us.gif 32 http://www.odci.gov/cia/publications/factbook/us.html 33 United States Information 34 20 35 /images/france.gif 36 http://www.odci.gov/cia/publications/factbook/fr.html 37 France Information 38 20 39 /images/germany.gif 40 http://www.odci.gov/cia/publications/factbook/gm.html 41 Germany Information 42 20 43 /images/italy.gif 44 http://www.odci.gov/cia/publications/factbook/it.html 45 Italy Information 46 20 47 /images/spain.gif 48 http://www.odci.gov/cia/publications/factbook/sp.html 49 Spain Information 50 20 config.txt Header includes image HEIGHT, image WIDTH and image BORDER width Asterisk separates header from advertisements Image location Destination URL ALT tag Percentage of time image appears
File System Object • File System Objects (FSOs) • Manipulate files, directories and drives • Read and write text • In Microsoft Scripting Runtime Library • 5 FSO types: • FileSystemObject • Interact with Files, Folders and Drives • File • Manipulate Files of any type • Folder • Manipulate Folders (i.e, directories) • Drive • Gather info about Drives (local or remote) • TextStream • Read and write text files
File System Object • OpenTextFile(filename, code, create) • filename - file to open • code • 8 - open for appending • 1 - open for reading • 2 - open for writing • create? - if true, creates a new file if does not exist
Quering Data <% 'Declare Variables Dim dcnDB 'As ADODB.Connection Dim rsDB 'As ADODB.Recordset Dim sqlQuery 'As String 'Find path of database file filePath = Server.MapPath("depkeu.MDB") 'Open Database Connection Set dcnDB = Server.CreateObject("ADODB.Connection") 'dcnDB.Open "DBName" - This is for an ODBC Datasource (if set up) or ' use the below code for opening a Access 2000 DB dcnDB.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="&filePath dcnDB.Open 'Query and create recordset sqlQuery = "SELECT * FROM Students ORDER BY LastName,FirstName" Set rsDB = Server.CreateObject("ADODB.Recordset") Set rsDB = dcnDB.Execute(sqlQuery) %>
Quering Data <% Do Until rsDB.EOF %> <tr> <td valign="top"><%=rsDB("StudentID")%></td> <td valign="top"><%=rsDB("FirstName")%> </td> <td valign="top"><%=rsDB("LastName")%></td> <td valign="top"> <!-- dynamically add variable values to hyperlink --> <a href="update_students.asp?StudentID=<%=rsDB("StudentID")%>">Update</a> </td> <td valign="top"> <!-- dynamically add variable values to hyperlink --> <a href="delete_students.asp?StudentID=<%=rsDB("StudentID")%>"><font color="red">Delete</font></a> </td> </tr> <% rsDB.MoveNext Loop %> </table>
Updating Data <% 'Declare Variables Dim dcnDB 'As ADODB.Connection Dim rsDB 'As ADODB.Recordset Dim sqlQuery 'As String Dim sqlUpdate 'As String Dim filePath 'As String 'Find path of database file filePath = Server.MapPath("depkeu.mdb") 'Open Database Connection Set dcnDB = Server.CreateObject("ADODB.Connection") 'dcnDB.Open "DBName" - This is for an ODBC Datasource (if set up) or ' use the below code for opening a Access 2000 DB dcnDB.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="&filePath dcnDB.Open
'Check for action If Request.Form("action") = "Update" Then 'Create SQL UPDATE statement from form fields sqlUpdate = "UPDATE Students " _ & "Set FirstName = '" & Request.Form("FirstName") & "'," _ & "LastName = '" & Request.Form("LastName") & "' " _ & "WHERE StudentID = '" & Request.Form("StudentID") & "'" 'Execute the query dcnDB.Execute(sqlUpdate) 'Notify action taken Response.Write "Record Updated<br><br>" End If 'Check for StudentID in URL Path If Request("StudentID") <> "" Then 'Create SQL String sqlQuery = "SELECT * FROM Students WHERE StudentID = '" & Request("StudentID") & "'" 'Query the database and create a recordset Set rsDB = Server.CreateObject("ADODB.Recordset") Set rsDB = dcnDB.Execute(sqlQuery) End If %>
ASP .NET • New version of ASP • Using .NET CLR • .aspx extension • ASP .Net is part of Visual Studio .Net
ASP .NET Code <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html>
ASP .Net Code Partial Class _Default Inherits System.Web.UI.Page Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Label1.Text = "Helo " & DropDownList1.Text & ", Selamat Belajar ASP .Net" End Sub End Class
Validation in ASP .Net ASP.NET provides validation controls to: • Compare values • Compare to a custom formula • Compare to a range • Compare to a regular expression pattern • Require user input • Summarize the validation controls on a page
Adding Validation Controls to a Web Form 1 • Add a validation control • Select the input control to validate • Set validation properties 2 3 <asp:TextBox id="txtName" runat="server" /> <asp:Type_of_Validator id="Validator_id" runat="server"ControlToValidate="txtName" ErrorMessage="Message_for_error_summary"Display="static|dynamic|none" Text="Text_to_display_by_input_control"> </asp:Type_of_Validator>
Positioning Validation Controls on a Web Form • Create error messages • Select display mode • Static • Dynamic
Combining Validation Controls • Can have multiple validation controls on a single input control • Only the RequiredFieldValidator checks empty controls
Input Validation Controls • RequiredFieldValidator • InitialValue • CompareValidator • ValueToCompare or ControlToCompare • Type • Operator • RangeValidator • MinimumValue • MaximumValue • Type Code Examples
Using the RegularExpressionValidator Control • Used when input must conform to a pre-defined pattern • Visual Studio .NET includes patterns for: • Telephone numbers • Postal codes • E-mail addresses <asp:RegularExpressionValidator … ControlToValidate="US_PhoneNumber"…ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4} " …>*</asp:RegularExpressionValidator >
Connecting to Database • Namespace used: System.Data.SqlClient and System.Data. • Classes used: SqlConnection, SqlDataAdapter and SqlCommand.
Connecting to database dim cn as sqlConnection cn= new SqlConection (“server=localhost;uid=“ &username.text & “;pwd=“&pass.value &”;database=pubs;”) try ‘open connection cn.open … catch sx as sqlException … end try cn.close
Using Templates with List-Bound Controls • Displaying Data in the Repeater and DataList Controls • Using Templates • Demonstration: Using a DataList Control
Displaying Data in the Repeater and DataList Controls • Create the control and bind it to a DataSet • Set custom properties • Autoformat • Columns (horizontal vs. vertical columns) • Display data in templates <asp:Repeater id="repList" runat="server"> <ItemTemplate> <%#DataBinder.Eval(Container.DataItem, "au_lname")%> </ItemTemplate> </asp:Repeater>
Using Templates HeaderTemplate ItemTemplate SeparatorTemplate AlternatingItemTemplate FooterTemplate