Pertemuan 3 Server Side Scripting (ASP & ASP.Net) Matakuliah: T0053/Web Programming Tahun: 2006 Versi: 2
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 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 – –Indicate code is to be executed on server, not –Specify scripting language (default VBScript) – Each time page refreshed, server loads and interprets ASP
2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1Specify VBScript as scripting language 1.2Use Option Explicit to indicate variables be explicitly declared by programmer 1.3Use META tag to set refresh interval Time gets current time on server (hh:mm:ss) Short for A Simple ASP Example Simple ASP Example
2000 Deitel & Associates, Inc. All rights reserved. Output from a simple Active Server Page
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
2000 Deitel & Associates, Inc. All rights reserved. Some server-side ActiveX components included with IIS and PWS
2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1Create instance of AdRotator component 1.2Call Response object’s Write method to send advertisement to client AdRotator Example AdRotator Example 13 14<% 15 ' Declare flagChanger 16 Dim flagChanger ' Create an AdRotator object 19 Set flagChanger = Server.CreateObject( "MSWC.AdRotator" ) ' Use config.txt to send an advertisement to the client 22 Call Response.Write( _ 23 flagChanger.GetAdvertisement( "config.txt" ) ) 24%> 25 26
2000 Deitel & Associates, Inc. All rights reserved. Outline config.txt 1.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 27WIDTH 54 28HEIGHT 36 29BORDER 1 30* 31/images/us.gif 32http:// 33United States Information /images/france.gif 36http:// 37France Information /images/germany.gif 40http:// 41Germany Information /images/italy.gif 44http:// 45Italy Information /images/spain.gif 48http:// 49Spain Information 5020
2000 Deitel & Associates, Inc. All rights reserved. Demonstrating the AdRotator ActiveX component
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 File s, Folder s and Drive s File –Manipulate File s of any type Folder –Manipulate Folder s (i.e, directories) Drive –Gather info about Drive s (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
2000 Deitel & Associates, Inc. All rights reserved. FileSystemObject methods
2000 Deitel & Associates, Inc. All rights reserved. Some common File properties and methods
2000 Deitel & Associates, Inc. All rights reserved. Some Folder properties and methods
2000 Deitel & Associates, Inc. All rights reserved. Drive properties
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 ">Update "> Delete <% rsDB.MoveNext Loop %>
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 " 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
Visual Studio.Net IDE
ASP.NET Code Untitled Page
Toolbox
Simple Form
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
Result
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 2. Select the input control to validate 3. Set validation properties <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 id="Validator_id" runat="server" ControlToValidate="txtName" ErrorMessage="Message_for_error_summary" Display="static|dynamic|none" Text="Text_to_display_by_input_control">
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 addresses <asp:RegularExpressionValidator … ControlToValidate="US_PhoneNumber"… ValidationExpression=" ((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4} " …>* <asp:RegularExpressionValidator … ControlToValidate="US_PhoneNumber"… ValidationExpression=" ((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4} " …>*
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
Using Templates FooterTemplate HeaderTemplate ItemTemplate SeparatorTemplate AlternatingItemT emplate