Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

45
Pertemuan 3 Server Side Scripting (ASP & ASP .Net) Matakuliah : T0053/Web Programming Tahun : 2006 Versi : 2

description

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. - PowerPoint PPT Presentation

Transcript of Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Page 1: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Pertemuan 3Server Side Scripting

(ASP & ASP .Net)

Matakuliah : T0053/Web Programming

Tahun : 2006

Versi : 2

Page 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

Page 3: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Material Outline

• Mengenal Server side scripting

• Pemrograman dasar ASP & ASP .Net

• Koneksi ke database

Page 4: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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.

Page 5: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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

Page 6: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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

Page 7: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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

Page 8: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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

Page 9: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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

Page 10: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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

Page 11: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.

Outline

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() ) %>

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 = ARIAL SIZE = 4><STRONG>Simple ASP Example</STRONG>

14</FONT><P>

15 <TABLE BORDER = "6">

16 <TR>

17 <TD BGCOLOR = "#000000">

18 <FONT FACE = Arial COLOR = "#00FF00" SIZE = 4>

19 <% =Time() %>

20 </FONT>

21 </TD>

22 </TR>

23 </TABLE>

24</BODY>

25</HTML>

Page 12: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.

Output from a simple Active Server Page

Page 13: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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

Page 14: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.

Some server-side ActiveX components included with IIS and

PWSComponent Name Description

MSWC.BrowserType ActiveX component for gathering information (e.g., type, version, etc.) about the client’s browser.

MSWC.AdRotator ActiveX component for rotating advertisements on a Web Page.

MSWC.NextLink ActiveX component for linking together Web pages.

MSWC.ContentRotator ActiveX component for rotating HTML content on a Web page.

MSWC.PageCounter ActiveX component for storing the number of times a Web page has been requested.

MSWC.Counters ActiveX components that provides general-purpose persistent counters.

MSWC.MyInfo ActiveX component that provides information (e.g., owner name, owner address, etc.) about a Web site.

Scripting.FileSystemObject ActiveX component that provide an object library for accessing files on the server or on the server’s network.

ActiveX Data Objects (ADO) Data Access Components

ActiveX components that provide an object library for accessing databases.

Page 15: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.

Outline

1.1 Create instance of AdRotator component

1.2 Call Response object’s Write method to send advertisement to client

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

16 Dim flagChanger

17

18 ' Create an AdRotator object

19 Set flagChanger = Server.CreateObject( "MSWC.AdRotator" )

20

21 ' Use config.txt to send an advertisement to the client

22 Call Response.Write( _

23 flagChanger.GetAdvertisement( "config.txt" ) )

24%>

25</BODY>

26</HTML>

Page 16: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

2000 Deitel & Associates, Inc. All rights reserved. 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

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

Page 17: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.

Demonstrating the AdRotator ActiveX component

Page 18: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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

Page 19: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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

Page 20: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.

FileSystemObject methods

Methods Description

CopyFile Copies an existing File.

CopyFolder Copies an existing Folder.

CreateFolder Creates and returns a Folder.

CreateTextFile Creates and returns a text File.

DeleteFile Deletes a File.

DeleteFolder Deletes a Folder.

DriveExists Tests whether or not a Drive exists.

FileExists Tests whether or not a File exists. Returns boolean.

FolderExists Tests whether or not a Folder exists. Returns boolean.

GetAbsolutePathName Returns the absolute path as a string. GetDrive Returns the specified Drive.

GetDriveName Returns the Drive drive name.

GetFile Returns the specified File.

GetFileName Returns the File file name.

GetFolder Returns the specified Folder.

GetParentFolderName Returns a string representing the parent folder name. GetTempName Creates and returns a string representing a file name. MoveFile Moves a File.

MoveFolder Moves a Folder.

OpenTextFile Opens an existing text File. Returns a TextStream.

Page 21: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.

Some common File properties and methods

Property/method Description

Properties

DateCreated Date. The date the File was created.

DateLastAccessed Date. The date the File was last accessed.

DateLastModified Date. The date the File was last modified.

Drive Drive. The Drive where the file is located.

Name String. The File name.

ParentFolder String. The File’s parent folder name.

Path String. The File’s path.

ShortName String. The File’s name expressed as a short name.

Size The size of the File in bytes.

Methods

Copy Copy the File. Same as CopyFile of FileSystemObject.

Delete Delete the File. Same as DeleteFile of FileSystemObject.

Move Move the File. Same as MoveFile of FileSystemObject.

OpenAsTextStream Opens an existing File as a text File. Returns TextStream.

Page 22: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.

Some Folder properties and methodsProperty/method Description

Properties Attributes Integer. Value indicating Folder’s attributes (read only, hidden, etc.)

DateCreated Date. The date the folder was created. DateLastAccessed Date. The date the folder was last accessed. DateLastModified Date. The date the folder was last modified. Drive Drive. The Drive where the folder is located.

IsRootFolder Boolean. Indicates whether or not a Folder is the root folder.

Name String. The Folder’s name.

ParentFolder String. The Folder’s parent folder name.

Path String. The Folder’s path.

ShortName String. The Folder’s name expressed as a short name.

ShortPath String. The Folder’s path expressed as a short path.

Size Variant. The total size in bytes of all subfolders and files. Type String. The Folder type.

Methods Delete Delete the Folder. Same as DeleteFolder of FileSystemObject.

Move Move the Folder. Same as MoveFolder of FileSystemObject.

Copy Copy the Folder. Same as CopyFolder of FileSystemObject.

Page 23: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.

Drive properties

Property Description

AvailableSpace Variant. The amount of available Drive space in bytes.

DriveLetter String. The letter assigned the Drive (e.g., “C”).

DriveType Integer. The Drive type. Constants Unknown, Removable, Fixed, Remote, CDRom and RamDisk represent Drive types and have the values 0–5, respectively.

FileSystem String. The file system Drive description (FAT, FAT32, NTFS, etc.).

FreeSpace Variant. Same as AvailableSpace.

IsReady Boolean. Indicates whether or not a Drive is ready for use.

Path String. The Drive’s path.

RootFolder Folder. The Drive’s root Folder.

SerialNumber Long. The Drive serial number.

TotalSize Variant. The total Drive size in bytes.

VolumeName String. The Drive volume name.

Page 24: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Quering Data

<%

'Declare VariablesDim dcnDB 'As ADODB.ConnectionDim rsDB 'As ADODB.RecordsetDim sqlQuery 'As String

'Find path of database filefilePath = Server.MapPath("depkeu.MDB")

'Open Database ConnectionSet 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 DBdcnDB.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="&filePathdcnDB.Open

'Query and create recordsetsqlQuery = "SELECT * FROM Students ORDER BY LastName,FirstName"Set rsDB = Server.CreateObject("ADODB.Recordset")Set rsDB = dcnDB.Execute(sqlQuery)

%>

Page 25: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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>

Page 26: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Updating Data

<%

'Declare VariablesDim dcnDB 'As ADODB.ConnectionDim rsDB 'As ADODB.RecordsetDim sqlQuery 'As StringDim sqlUpdate 'As StringDim filePath 'As String

'Find path of database filefilePath = Server.MapPath("depkeu.mdb")

'Open Database ConnectionSet 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 DBdcnDB.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="&filePathdcnDB.Open

Page 27: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

'Check for actionIf Request.Form("action") = "Update" Then

'Create SQL UPDATE statement from form fieldssqlUpdate = "UPDATE Students " _

& "Set FirstName = '" & Request.Form("FirstName") & "'," _& "LastName = '" & Request.Form("LastName") & "' " _& "WHERE StudentID = '" & Request.Form("StudentID") & "'"

'Execute the querydcnDB.Execute(sqlUpdate)

'Notify action takenResponse.Write "Record Updated<br><br>"

End If

'Check for StudentID in URL PathIf Request("StudentID") <> "" Then

'Create SQL StringsqlQuery = "SELECT * FROM Students WHERE StudentID = '" & Request("StudentID") & "'"

'Query the database and create a recordsetSet rsDB = Server.CreateObject("ADODB.Recordset")Set rsDB = dcnDB.Execute(sqlQuery)

End If%>

Page 28: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

ASP .NET

• New version of ASP

• Using .NET CLR

• .aspx extension

• ASP .Net is part of Visual Studio .Net

Page 29: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Visual Studio .Net IDE

Page 30: Pertemuan 3 Server Side Scripting (ASP & ASP .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>

Page 31: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Toolbox

Page 32: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Simple Form

Page 33: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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 SubEnd Class

Page 34: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Result

Page 35: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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

Page 36: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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>

<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>

<asp:TextBox id="txtName" runat="server" /><asp:TextBox id="txtName" runat="server" />

1111

2222

3333

Page 37: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Positioning Validation Controls on a Web Form

Create error messages Select display mode

Static

Dynamic

Page 38: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Combining Validation Controls

Can have multiple validation controls on a single input control

Only the RequiredFieldValidator checks empty controls

Page 39: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Input Validation Controls

RequiredFieldValidator InitialValue

CompareValidator ValueToCompare or ControlToCompare Type Operator

RangeValidator MinimumValue MaximumValue Type

Code Examples

Page 40: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

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 >

<asp:RegularExpressionValidator …ControlToValidate="US_PhoneNumber"…ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4} "…>*</asp:RegularExpressionValidator >

Page 41: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Connecting to Database

Namespace used:

System.Data.SqlClient and System.Data.

Classes used:

SqlConnection, SqlDataAdapter and SqlCommand.

Page 42: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Connecting to database

dim cn as sqlConnectioncn= new SqlConection (“server=localhost;uid=“

&username.text & “;pwd=“&pass.value &”;database=pubs;”)

try‘open connectioncn.open…catch sx as sqlException…end trycn.close

Page 43: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Using Templates with List-Bound Controls

Displaying Data in the Repeater and DataList Controls

Using Templates

Demonstration: Using a DataList Control

Page 44: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Displaying Data in the Repeater and DataList Controls

<asp:Repeater id="repList" runat="server"><ItemTemplate> <%#DataBinder.Eval(Container.DataItem, "au_lname")%></ItemTemplate></asp:Repeater>

<asp:Repeater id="repList" runat="server"><ItemTemplate> <%#DataBinder.Eval(Container.DataItem, "au_lname")%></ItemTemplate></asp:Repeater>

Create the control and bind it to a DataSet

Set custom properties

Autoformat

Columns (horizontal vs. vertical columns)

Display data in templates

Page 45: Pertemuan 3 Server Side Scripting (ASP & ASP .Net)

Using Templates

FooterTemplateFooterTemplate

HeaderTemplateHeaderTemplate

ItemTemplateItemTemplate

SeparatorTemplateSeparatorTemplate

AlternatingItemTemplateAlternatingItemTemplate