Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

67
Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Transcript of Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Page 1: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Web-Based Applications

Using

ASP.NETDr. Awad Khalil

Computer Science & Engineering Department

AUC

Page 2: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Objectives Web application development using ASP.NET To create Web forms. To create ASP.NET application consisting of multiple

Web forms. To maintain state information about a user with session

tracking and cookies. To use the Web Site Administration Tool to modify Web

application configuration settings. To control user access to Web application using forms

authentication and ASP.NET login controls. To use databases in ASP.NET applications. To design a master page and content pages to create a

uniform look-and-feel for a Web site.

Page 3: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Introduction

• ASP.NET– Server-side technology that dynamically builds

documents in response to client requests.

– Can be used on a server to create Web applications.

– Supports over 25 programming languages.

– ASP.NET takes advantage of .NET Framework, which provides thousands of classes that deal with XML, text input, validation of user input, image processing, and more.

– ASP.NET also simplifies Web Services programming.

– Object-oriented programming.

Page 4: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

  .NET Overview • Independent from a specific programming language.• Programmers can contribute to the same application,

writing the code in any .NET-compatible languages (such as VB.NET, Visual C++.NET, and C#).

• Promotes software reuse.• Include tools for porting, adapting existing software

components.• Web services, which are central to .NET initiative, extend

the concept of Software reuse to the Internet by allowing developers to reuse software components that reside on another machine or platform.

• For example, a company developing an e-commerce application can subscribe to Web services that process payments and authenticate users – this enables programmers to focus on other unique aspects of the e-commerce application.

Page 5: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

 .NET Framework

• The .NET Framework is at the heart of the .NET strategy.

• It manages and executes applications, provides a class library, enforces security and supplies many other programming capabilities.

• Framework Class Library (FCL)– Enforces security and supplies many other programming

capabilities

– Reusable components that programmers can incorporate into their applications

• Common Language Runtime (CLR)– Executes programs written in any .NET-compatible

programming language

• .NET Compact Framework.

Page 6: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

 .NET Compact Framework

• .NET Compact Framework enables developers to create applications for limited-resource devices, such as mobile phones and PDAs.

• Applications built using the Compact Framework can run on any device that has the Compact Framework installed.

• Users download applications onto a device through a wireless Internet connection or a connection from a PC. Once downloaded to the device, many applications do not require an Internet connection.

Page 7: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

 Common Language Runtime (CLR)

• CLR executes programs written in any .NET-compatible programming language.

• .NET programs are compiled in two steps:– First, a program is compiled into Microsoft

Intermediate Language (MSIL), which defines instructions for the CLR. Code translated into MSIL from multiple programming languages and sources can be woven together by the CLR.

– MSIL then is compiled into machine code for a specific platform.

Page 8: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

ASP (Active Server Pages) .NET

• ASP.NET another integral part of the .NET initiative, is a technology for creating dynamic Web content marked up as HTML.

• ASP.NET developers can create multi-tier, database-intensive applications quickly by employing .NET’s object-oriented languages and the FCL’s Web controls (technically known as ASP.NET server controls).

• Web controls look like HTML elements but are designed specifically for ASP.NET applications.

• Includes optimizations for performance, testing and security

• ASPX files• XHTML documents

– Static

Page 9: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

ASPX Files • ASP.NET applications consist of several file types.• The first is .aspx, which we refer to as ASPX files.• ASPX files contain the graphical user interface of a page, and may

also contain the logic of the page (in the form of scripts written in a .NET-compatible language).

• These scripts are usually separated from the portion of the ASPX file that defines the page’s GUI.

• ASPX files often have a corresponding code-behind file that contains a class written in a .NET language, such as C#. This class includes initialization code, utility methods and other supporting code that provides the ASPX file’s programmatic implementation.

• Code-behinds help separate the business logic code from the presentation code.

• Code-behinds written in C# typically have an .aspx.cs extension and are usually used in the middle tier of a three-tier Web-based application.

Page 10: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Structure of Web-Based Applications Web-based applications create Web content for Web browsers clients.

This Web content includes Extensible HyperText Markup Language (XHTML), client-side scripting, images and binary data.

We develop Web applications using Web forms, Web controls (also called ASP.NET server controls) and C# programming.

Web form files have the filename extension .aspx and contain the Web page’s GUI and we commonly refer to Web Form files as ASPX files.

We customize Web forms by adding Web controls including labels, text boxes, images, buttons, and other GUI components.

The Web form file represents the Web page that is sent to the client browser.

Page 11: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Structure of Web-Based Applications Every ASPX created in Visual Studio has a corresponding class

written in .NET language, such as C#. This class contains event handlers, initialization code, utility methods and other supporting code.

The file that contains this class is called the code-behind file and provides the ASPX file’s programmatic implementation.

Page 12: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Code-Behind Approach

• ASP.NET supports two methods of adding scripts to make static content dynamic:– The Inline code method: which embeds scripts within script elements in the .aspx file.

– The Code-Behind method: which separates the GUI of an ASP.NET page from the dynamic scripts (e.g., JScript.NET or C# code) that control the behavior of the application.

• Using code-behind enables the presentation code and programming logic to be placed in their own files. The approach allows the look and feel of a page to be modified easily without disrupting the “code-behind” the page, and vice versa. ASP.NET pages (with .aspx extensions) implement the Web site GUI, while C# code-behind files (with aspx.cs extensions) handle the pages’ event handlers and logic.

Page 13: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Code-Behind Approach

• A code-behind is not included in the .aspx file and must be compiled first. Then the .aspx file can call methods from the binary dynamic link library (DLL) that the compiler creates. A DLL is a library of functions or data that can be used by an application. Using the code-behind model ensures that every file is written either entirely in JScript.NET or entirely using XHTML and ASP.NET Web Form controls.

Page 14: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Simple HTTP Transaction Web application development requires a basic understanding of

networking and the World Wide Web. HTTP specifies a set of methods and headers that allow clients and

servers to interact and exchange information in a uniform and predictable manner.

In its simpler form, a Web page is nothing more than an XHTML document – a plain text file containing markup (i.e., tags) that describe to a Web browser how to display and format the document’s information. For example, the XHTML markup

<title>My Web Page</title>

indicates that the browser should display the text between the <title> start tag and the </title> end tag in the browser’s title bar.

XHTML documents also contain hypertext data (usually called hyperlinks), which links to different pages or to other parts of the same page. When the user activates a hyperlink (usually by clicking it with the mouse), the requested Web page loads into the user’s browser window.

Page 15: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Simple HTTP Transaction Any XHTML document available for viewing over the Web has a

corresponding Uniform Resource Locator (URL).

A URL is an address indicating the location of an Internet resource, such as an XHTML document.

The URL contains information that directs a browser to the sequence the user wishes to access. Computers that run Web server software make such resources available.

When requesting ASP.NET Web applications, the Web server is usually Microsoft Internet Information services (IIS).

Page 16: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Simple HTTP Transaction Let us examine the components of the URL:

http://www.deitel.com/books/downloads.html The http:// indicates that the resource is to be obtained using the HTTP protocol. The middle portion www.deitel.com is the server’s fully qualified hostname – the

name of the computer on which the resource resides. This computer usually is referred to as the host, because it houses and maintains resources. The hostname www.deitel.com is translated into an IP address (68.236.123.125), which identifies the server in a manner similar to how a telephone number uniquely defines a particular phone line. The hostname is translated into an IP address by a domain name system (DNS) server – a computer that maintains a database of hostnames and their corresponding IP address. This translation operation is called a DNS lookup.

The remainder of the URL (i.e., /books/downloads.html) specifies both the name of the requested resource (the XHTML document downloads.html) and its path, or location (/books), on the Web server. The path could specify the location of an actual directory on the Web server’s file system. However, for security reasons, the path often specifies the location of a virtual directory. In such systems, the server translates the virtual directory into a real location of the resource (or on another computer on the server’s network), thus hiding the true location of the resource.

Page 17: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Simple HTTP Transaction When given a URL, a Web browser performs a simple HTTP transaction to retrieve

and display the Web page found at that address. This transaction consists of interaction between the Web browser (the client side)

and the Web server application (the server side). The Web browser sends an HTTP request to the server. The request (in its simplest

form) is

GET /books/dowbloads.html HTTP/1.1

The word GET is an HTTP method indicating that the client wishes to obtain a resource from the server. The remainder of the request provides the path name of the resource (an XHTML document) and the protocol’s name and version number (HTTP/1.1).

Any server that understands HTTP (version 1.1) can translate this request and respond appropriately . The server first responds by sending a line of text that indicates the HTTP version, followed by a numeric code and a phrase describing the status of the transaction , for example:

HTTP/1.1 200 OK indicates success, wheras

HTTP/1.1 404 Not Found informs the client the Web server could not locate the required resource.

Page 18: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Simple HTTP Transaction The server then sends one or more HTTP headers, which provide additional

information about the data that will be sent. In this case, the server is sending an XHTML text document, so the HTTP header for this example reads:

Content-type: text/html

The information provided in this header specifies the Multipurpose Internet Mail Extensions (MIME) type of the content that the server is transmitting to the browser. MIME is an Internet standard that specifies data formats so that programs can interpret data correctly. For example, the MIME type text/plain indicates that the sent information is text that can be displayed directly, without any interpretation of the content as XHTML markup. Similarly, the MIME type image/jpeg indicates that the content is a JPEG image. When the browser receives this MIME type, it attempts to display the image.

The header or set of headers is followed by a blank line, which indicates to the client that the server is finished sending HTTP headers.

The server then sends the contents of the requested XHTML document (downloads.html).

The server terminates the connection when the resource transfer is complete. At this point, the client-side browser parses the XHTML markup it has received and

renders (or displays) the results.

Page 19: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Multitier Application Architecture Web-based applications are multitier applications (sometimes referred to as n-tier

applications). Multitier applications divide functionality into separate tiers (i.e., logical groupings of functionality).

Although tiers can be located on the same computer, the tiers of Web-based applications typically reside on separate computers.

The information tier (also called the data tier or the bottom tier) maintains data pertaining to the application. This tier typically stores data in a relational database management system (RDBMS). This tier can contain multiple databases, which together comprise the data needed for the Web-based application.

The middle tier implements business logic, controller logic and presentation logic to control interaction between the application’s clients and the application’s data. The middle tier acts as an intermediary between data in the information tier and the application’s clients.

The middle-tier controller logic processes client requests (such as requests to view a product catalog) and retrieves data from the database.

The middle-tier presentation logic then processes data from the information tier and presents the content to the client. Web applications typically present data to clients as XHTML documents.

Page 20: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Multitier Application Architecture Business logic in the middle tier enforces business rules and ensures that data is

reliable before the server application updates the database or presents the data to users. Business rules dictate how clients can and cannot access application data, and how applications process data. For example, a business rule in the middle tier of a retail store’s Web-based application might ensure that all product quantities remain positive. A client request to set a negative quantity in the bottom tier’s information database would be rejected by the middle tier’s business logic.

The client tier, or top tier, is the application’s user interface, which gathers input and displays output. Users interact directly with the application through the user interface, which is typically a Web browser, keyboard and mouse.

In response to user actions (e.g., clicking a hyperlink), the client tier interacts with the middle tier to make requests and to retrieve data from the information tier. The client tier then displays the data retrieved from the middle tier to the user.

The client tier never directly interact with the information tier.

Page 21: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

21

System Architecture

• Web server part of multi-tier application– Divide functionality into separate tiers

• Logical groupings of functionality

• Can reside on same computer or on different computers

• Following diagrams illustrates 3-tier application

Page 22: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

22

System Architecture

ApplicationMiddle tier

Information tie r

C lient tie r

Database

Three-tier application model.

Page 23: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

23

System Architecture (Cont’d)

• Information tier– Referred to as data tier or bottom tier

– Maintains data for application

– Stores data in relational database management system

• Middle tier– Implements business logic and presentation logic

– Controls interactions between application clients and application data

– Acts as intermediary between data in information tier and application clients

Page 24: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

24

System Architecture (Cont’d)

• Middle tier, cont.– Controller logic

• Processes client requests from top tier

• Retrieves data from database

– Presentation logic• Processes data from information tier

• Presents content to client

– Business logic• Enforces business rules

– Dictates how clients can access application data and how applications process data

• Ensures data validity before updating database

Page 25: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

25

System Architecture (Cont’d)

• Client tier– Referred to as top tier

– Application’s user interface

– Users interact with application through user interface

– Interacts with middle tier to make requests and to retrieve data from information tier

– Displays data to user

Page 26: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

26

Client-Side Scripting versus Server-Side Scripting

• Client-side scripting– Validates user input

– Accesses the browser

– Enhances Web pages with ActiveX® controls, applets, etc.

– Manipulates browser documents

• Client-side validation– Reduces number of requests that need to be passed to server

• Client-side scripting limitations– Browser dependency

– Viewable to users through View Source command

• JavaScript most popular client-side script

Page 27: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

27

Client-Side Scripting versus Server-Side Scripting (Cont’d)

• Server-side scripts– Provides programmers greater flexibility

– Generates custom responses for clients

– Contains greater programmatic capabilities than client-side equivalents

– Has access to server-side software that extend server functionality

Page 28: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

28

Web Server

• Web server– Specialized software that responds to client requests by

providing resources

– When users enter URL into Web browsers, they request specific documents from Web server

– Maps URL to file on server and returns requested document to client

– Communicates with client using HTTP• Protocol for transferring requests and files over the Internet

• Introduce two Web servers– Internet Information Services (IIS) and Apache Web Server

Page 29: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

29

Web Servers

IIS Apache

Company Microsoft Corporation

Apache Software Foundation

Version 5.1 1.3.20

Released 2/17/00 5/21/01

Platforms Windows 2000 Windows XP

UNIX, Windows NT/2000, experimentally supports Windows 95/98

Brief description

The most popular Web server for Windows 2000 & XP

Currently the most popular Web server.

Price Included with Windows 2000 & XP

Freeware.

Page 30: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

30

HTTP Request Types

• Also known as request methods• Most popular are get and post

– Retrieve and send client form data to Web server

– get request • Sends form content as part of URL

• Retrieves appropriate resource from Web server

• Limits query to 1024 characters

– post request• Updates contents of Web server (posting new messages to

forum)

• Has no limit for length of query

• Not part of URL and cannot be seen by user

Page 31: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

31

HTTP Request Types (Cont’d)

• Posts data to server-side form handler • Browsers cache (save on disk) Web pages

– Allows for quick reloading

– Cache responses to get request

– Do not cache responses to post request

Page 32: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

32

Accessing Web Servers

• Requesting documents– Must know machine name on which Web server resides

– Through local Web servers or remote Web servers

– Through domain name or Internet Protocol (IP) address

• Local Web server– Resides on users’ machines

– Requests documents in two ways• Machine name• localhost

– Host name that references local machine

Page 33: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

33

Accessing Web Servers (Cont’d)

• Remote Web server– Resides on different machines

• Domain name– Represents group of hosts on Internet

– Combines with how name (www) and top-level domain to from fully qualified host name

• Top-level domain (TLD)– Describes type of organization that owns domain name

• .com or .org

• Fully qualified host name– Provides user friendly way to identify site on Internet

Page 34: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

34

Accessing Web Servers (Cont’d)

• IP address– Unique address for locating computers on Internet

• Domain name server (DNS)– Maintains database of host names and corresponding IP

addresses

– Translates fully qualified host name to IP address• Known as DNS lookup

Page 35: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

35

Microsoft Internet Information Services (IIS)

• IIS 5.1– Enterprise-level Web server

– Included with Windows 2000 & Windows XP

– Allows computer to serve documents

• Internet Services Manager– Open Control Panel, double click Administrative Tools

icon, then double click Internet Services Manager icon

– Administration program for IIS

– Place documents to be requested in default directory or virtual directory

• Default: C:\Inetpub\Wwwroot• Virtual: alias for existing directory on local machine

Page 36: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

36

Microsoft Internet Information Services (IIS)

Internet Services Manager dialog.

Page 37: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

37

Microsoft Internet Information Services (IIS)

• Default FTP Site and Default Web Site– Permit transferring documents between computer and server

– HTTP used frequently to request documents

• Default SMTP Virtual Server– Allows for creation of mail server

• Create virtual directory in Default Web Site– Most Web documents reside in Webpub directory

• Right click Webpub, select New, then Virtual Directory• Initiates Virtual Directory Creation Wizard

– Guides user through virtual directory creation process

Page 38: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

38

Microsoft Internet Information Services (IIS)

Fig. 4 Virtual Directory Creation Wizard welcome dialog.

Page 39: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

39

Microsoft Internet Information Services (IIS)

• Virtual Directory Alias – Enter name for virtual directory

• Name should not conflict with an existing virtual directory

• Web Site Content Directory – Enter path of directory containing Web documents

• Access Permissions – Presents security level choices

– Select access level appropriate for Web document

Page 40: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

40

Microsoft Internet Information Services (IIS)

Virtual Directory Alias dialog.

Page 41: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

41

Microsoft Internet Information Services (IIS)

Web Site Content Directory dialog.

Page 42: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

42

Microsoft Internet Information Services (IIS)

• Access Permissions – Presents security level choices

– Select access level appropriate for Web document

– Read allows users to read and download files

– Run Scripts allows scripts to run in directory

– Execute allows applications to run in directory

– Write allows Web page to accept user input

– Browse allows users to navigate between documents

– Read and Run Scripts selected by default

Page 43: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

43

Microsoft Internet Information Services (IIS)

Access Permissions dialog.

Page 44: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

44

Apache Web Server

• Apache– Maintained by Apache Software Foundation

– Currently most popular Web server• Stable

• Efficient

• Portable

Page 45: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

45

Support of Different Technologies

• IIS supports ASP.NET documents• Apache Does not support ASP.NET documents• IIS and Apache support Perl documents• IIS and Apache support Python documents• IIS and Apache support PHP documents

Page 46: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Commonly Used ASP.NET Objects

• An ASP.NET application when compiled, actually defines a class.

• The class inherits from class Page, provided by the .NET Framework.

• By inheriting from the Page class, the ASP.NET application gains access to several built-in objects that enable programmers to communicate with a Web browser, gather data sent by an HTTP request and distinguish between users.

Object Name Description Request Used to access information passed by an HTTP request. Response Used to control the information sent to the client. Server Used to access methods and properties on the server.

Page 47: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Web Forms • ASPX files are usually referred to as Web Forms or Web Form Pages because they normally process form input.

• Data entered into a form can be sent to the server, processed, then sent back to the client in different format.

• The first time a Web form is requested, the entire page is compiled. Later requests are served from the compiled page and do not have to be recompiled.

• Technically, any text file with an .aspx extension is an ASP.NET Web Forms page.

• Any pure HTML page can be given an .aspx extension and run as an ASP.NET page.

• Programmers customize Web Forms by adding Web controls, which include labels, text boxes,, images, buttons and other GUI components.

Page 48: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Web Controls

• Web controls normally have the attribute runat = “server” and are included within an ASP.NET Web Form designated by the <form> tag.

• There are four types of Web controls:– HTML server controls

• Programmable HTML elements run on the server

– Web server controls• Form-like controls such as drop-down lists and text boxes

– Validation controls (validators)• Required field validator

• Range validator

– User controls• Created by programmer

Page 49: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Web Controls

HTML Server Control

Description

HtmlAnchor Navigation link. HtmlButton Customizable input button. HtmlTable Programmatically built table. HtmlInputFile Handles uploading of files from client to server. HtmlImage Renders images. HtmlForm User-input form.

HTML server controls.

Web Server Control

Description

AdRotator Presents ad images and ad banners. DataGrid Displays tabular data and supports selecting, sorting

and editing data. TextBox Enables user to enter text. HyperLink Creates a link to another document. DropDownList Provides a single-select drop-down list. Calendar Displays a month calendar from which users can

select dates. Web server controls.

Page 50: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Web Controls

Server Control Description RequiredFieldValidator Checks that the user does not leave a

field blank. CompareValidator Compares an input value with

another value. The value being compared to may be another control’s input value.

RangeValidator Checks that a user’s entry is within a specified range.

RegularExpressionValidator Checks that the entry matches a regular expression pattern.

ValidationSummary Displays the validation errors for all the validation controls on a page.

Validation server controls.

Page 51: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Creating and Running a Simple Web-Form Example

Our first example displays the Web server’s time in a browser window. When run, this program displays the text A Simple Web Form example, followed by the Web server’s time.

The program consists of two related files - an ASPX file and a C# code-behind file.

Page 52: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

1. <%-- WebTime.aspx --%>

2. <%-- A page that displays the current time in a Label. --%>

3. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebTime.aspx.cs"

4. Inherits="WebTime" EnableSessionState="False" %>

5.  

6. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

7. "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

8.  

9. <html xmlns="http://www.w3.org/1999/xhtml" >

10. <head id="Head1" runat="server">

11. <title>A Simple Web Form Example</title>

12. </head>

13. <body>

14. <form id="form1" runat="server">

15. <div>

16. <h2>Current time on the Web server:</h2>

17. <p>

18. <asp:Label ID="timeLabel" runat="server" BackColor="Black"

19. Font-Size="XX-Large" ForeColor="Yellow"

20. EnableViewState="False"></asp:Label>

21. </p>

22. </div>

23. </form>

24. </body>

25. </html>

Page 53: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

The ASPX file contains other information in addition to XHTML. Lines 1-2 are ASP.NET comments that indicate the example number, file name and

the purpose of the file. ASP.NET comments begin with <%-- and terminate with --%>. Lines 3-4 use a Page directive (in an ASPX file a directive is delimited by <%@

and %>) to specify information needed by ASP.NET to process this file. The Language attribute of the Page directive specifies the language of the code-behind file as C#; the code-behind file (i.e., the CodeFile) is WebTime.aspx.cs. Note that a code-behind file name usually consists of the full ASPX file name (e.g., WebTime.aspx) followed by the .cs extension.

The AutoEventWireup attribute (line 3) determines how Web Form events are handled. When AutoEventWireup is set to true, ASP.NET determines which methods in the class are called in response to an event generated by the page. For example, ASP.NET will call methods Page_Load and Page_Init in the code-behind file to handle the Page’s Load and Init events respectively.

Examining an ASPX File

Page 54: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

The inherits attribute (line 4) specifies the class in the code-behind file from which this ASP.NET class inherits – in this case, WebTime.

Lines 6-7 contain a document type declaration, which specifies the document element name (HTML) and the PUBLIC Uniform Identifier (URI) for the DTD that defines the XHTML vocabulary.

Lines 9-10 contain the <html> and <head> start tags, respectively. XHTML documents have the root element html and mark up information about the document in the head element. Also note that the html element specifies the XML namespace of the document using the xmlns attribute.

Line 11 sets the title of the Web page. Notice the runat attribute in line 10, which is set to “server” . This attribute indicates that when a client requests this ASPX file, ASP.NET processes the head element and its nested element on the server and generates the corresponding XHTML, which is then sent to the client. In this case, the XHTML sent to the client will be identical to the markup in the ASPX file. However, ASP.NET can generate complex XHTML markup from simple elements in an ASPX file.

Creating and Running a Simple Web-Form Example

Page 55: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Line 13 contains the <body> start tag, which begins the body of he XHTML document; the body contains the main content that the browser displays. The form that contains the XHTML text and controls is defined in lines 14-23.

Again, the runat attribute in the form element indicates that this element executes on the server, which generates equivalent XHTML and sends it to the client.

Lines 15-22 contain a div element that groups the elements of the form in a block of markup.

Line 16 is an h2 heading element that contains text indicating the purpose of the Web page.

Lines 17-21 contain a p element to mark up content to be displayed as a paragraph in the browser.

Lines 18-20 mark up a Label Web control. The properties that we set in the properties window, such as Font-Size and BackColor (i.e., background color), are attributes here. The ID attribute (line 18) assigns a name to the control so that it can be manipulated programmatically in the code-behind file. We set the control’s EnableViewState attribute (line 20) to False.

Creating and Running a Simple Web-Form Example

Page 56: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

The asp: tag prefix in the declaration of the label tag (line 18) indicates that the label is an ASP.NET Web control, not an XHTML element .

Each Web control maps to a corresponding XHTML element (or group of elements) – when processing a Web control on the server, ASP.NET generates XHTML markup that will be sent to the client to represent that control in a Web browser.

In this example, the asp:Label control maps to the XHTML span element (i.e., ASP.NET creates a span element to represent this control in the client’s Web browser).

A span element contains text that is displayed in a Web page. This particular element is used because span elements allow formatting styles to be applied to text.

Several of the property values that were applied to the label are represented as part of the style attribute of the span element.

The Web control in this example contains the runat=“server” attribute – value pair (line 18), because this control must be processed on the server so that the server can translate the control into XHTML that can be rendered in the client browser. If this attribute pair is not present, the asp:Label element is written as text to the client (i.e. the control is not converted into a span element and does not render properly).

Creating and Running a Simple Web-Form Example

Page 57: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

1. // WebTime.aspx.cs

2. // Code-behind file for a page that displays the current time.

3. using System;

4. using System.Data;

5. using System.Configuration;

6. using System.Web;

7. using System.Web.Security;

8. using System.Web.UI;

9. using System.Web.UI.WebControls;

10. using System.Web.UI.WebControls.WebParts;

11. using System.Web.UI.HtmlControls;

12.  

13. public partial class WebTime : System.Web.UI.Page

14. {

15. // initializes the contents of the page

16. protected void Page_Init( object sender, EventArgs e )

17. {

18. // display the server's current time in timeLabel

19. timeLabel.Text = String.Format( "{0:D2}:{1:D2}:{2:D2}",

20. DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second );

21. } // end method Page_Init

22. } // end class WebTime

Page 58: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Line 13 begins by declaration of class WebTime. Recall that a class declaration can span multiple source-code files and that the separate portions of the class declaration in each file are known as partial classes. The partial modifier in line 13 indicates that the code-behind file actually is a partial class.

Line 13 indicates that WebTime inherits from class Page in namespace System.Web.UI. This namespace contains classes and controls that assist in building Web-based applications. In addition to class Page (from which all Web applications directly or indirectly inherit), System.Web.UI also includes class Control – the base class that provides common functionality for all Web controls.

Lines 16-21 define method Page_Init, which handles the page’s Init event. This event – the first event raised after a page is requested – indicates that the page is ready to be initialized. The only initialization required for this page is setting timeLabel’s Text property to the time of the server (i.e., the computer on which executes).

The statements in lines 19-20 retrieves the current time and formats it as HH:MM:SS. For example, 9 AM is formatted as 09:00:00, and 2:30 PM is formatted as 14:30:00. Notice that the code-behind file can access timeLabel (the ID of the Label in the ASPX file) programmatically, even though the file does not contain a declaration for a variable named timeLabel.

Examining a Code-Behind File

Page 59: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

How are the ASPX and code-behind files used to create the Web page that is sent to the client? First, recall that class WebTime is the base class specified in line 3 of the ASPX file. This class (partially declared in the code-behind file) inherits from Page, which defines the general functionality of a Web page. Partial class WebTime inherits this functionality and defines some of its own (i.e., displaying the current time). The code-behind file contains the code to retrieve and display the time, whereas the ASPX file contains the code to define the GUI.

When a client requests an ASPX file, ASP.NET creates two classes behind the scenes. Recall that the code-behind file contains a partial class named WebTime. The first file ASP.NET generates is another partial class containing the remainder of class WebTime, based on the markup in the ASPX file. For example, WebTime.aspx contains a Label Web control with ID timeLabel, so the generated partial class would contain a declaration for a Label variable named timeLabel. This partial class might look like:

public partial class WebTime

{

protected System.Web.UI.WebControls.Label timeLabel;

}

Relationship Between an ASPX File and a Code-behind File

Page 60: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

Note that a Label is a Web control defined in namespace System.Web.UI.WebControls, which contains Web controls for designing a page’s user interface. Web controls in this namespace derive from class WebControls.

When compiled, the preceding partial class declaration containing Web control declarations combines with the code-behind file’s partial class declaration to form the complete WebTime class. This explains why line 19 in method Page_Init of WebTime.aspx.cs can access timeLabel, which is created in lines 18-20 of WebTime.aspx – method Page_Init and control timeLabel are actually members of the same class, but defined in separate partial classes.

The second class generated by ASP.NET is based on the ASPX file that defines the page’s visual representation . This new class inherits from class WebTime, which defines the page’s logic.

The first time the Web page is requested, this class is compiled, and an instance is created. This instance represents our page – it creates the XHTML that is sent to the client. The assembly created from our compiled classes is placed within a subdirectory of:

C:\WINDOWS\Microsoft\Framework\VersionNumber\Temporary ASP.NET FILES\WebTime

Relationship Between an ASPX File and a Code-behind File

Page 61: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

When an instance of the page is created, the Init event occurs first, invoking method Page_Init. Method Page_Init can contain code needed to initialize objects and other aspects of the page.

After the Page_Init executes, the Load event occurs, and the Page_Load event handler executes. Although not present in this example, this event is inherited from class Page.

After this event handler finishes executing, the page processes events that are generated by the page’s controls, such as user interaction with the GUI.

When the Web Form object is ready for garbage collection, an Unload event occurs, which calls the Page_Unload event handler. This event, too, is inherited from the class Page.

Page_Unload typically contains code that releases resources used by the page

How the Code-behind in an ASP.NET Page Executes

Page 62: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

2. "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

3. <html xmlns="http://www.w3.org/1999/xhtml" >

4. <head id="Head1"><meta HTTP-EQUIV="REFRESH" content="5; URL=WebTime.aspx" /><title>

5. A Simple Web Form Example

6. </title></head>

7. <body>

8. <form name="form1" method="post" action="WebTime.aspx" id="form1">

9. <div>

10. <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"

11. value="/wEPDwUJNTAzNTEzNDc4ZGTqPKK4tIBd3lQ9vsx4FLcWA4gSQA==" />

12. </div>

13. <div>

14. <h2>Current time on the Web server:</h2>

15. <p>

16. <span id="timeLabel" style="color:Yellow;

17. background-color:Black;font-size:XX-Large;">

18. 15:29:01</span>

19. </p>

20. </div>

21. </form>

22. </body>

23. </html>

Examining the XHTML Generated by ASP.NET Application

Page 63: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

The contents of the XHTML file generated by ASP.NET when WebTime.aspx is requested by a client Web browser, are similar to those of the ASPX file.

Notice that an XHTML form is the main mechanism for collecting user information and sending it to the Web server. In this particular example, the user does not submit data to the Web server for processing; however, processing user data is a crucial part of many applications that is facilitated by the form.

XHTML forms can contain visual and nonvisual components. Visual components include clickable buttons and other GUI components with which the users interact . Nonvisual components, called hidden Inputs, store data, such as e-mail addresses, that the document author specifies. One of these hidden inputs is defined in lines 10-11.

Attribute method of the form element (line 8) specifies the method by which the Web browser submits the form to the server.

The action attribute identifies the name and location of the resource that will be requested when this form is submitted – in this case, WebTime.aspx.

Recall that the ASPX file’s form element contained the runat=“server” attribute-value pair. When the form is processed on the server, the runat attribute is removed. The method and action attributes are added, and the resulting XHTML form is sent to the client browser.

Examining the XHTML Generated by ASP.NET Application

Page 64: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

In the ASPX file, the form’s Label (i.e., timeLabel) is a Web control. Here, we are viewing the XHTML created by our application , so the form contains a span element (lines 16-18) to represent the text in the label.

In this particular case, ASP.NET maps the Label Web control to an XHTML span element. The formatting options that were specified as properties of timeLabel, such as the font size and color of the text in the Label, are now specified in the style attribute of the span element.

Notice that only those elements in the ASPX file marked with the runat=“server” attribute-value pair or specified as Web controls are modified or replaced when the file is processed by the server.

The pure XHTML elements, such as the h2 in line 14, are sent to the browser exactly as they appear in the ASPX file

Examining the XHTML Generated by ASP.NET Application

Page 65: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

1. <%@ Page Language="C#" %>

2. <%@ Import namespace = "System" %>

3. <%@ Import namespace = "System.Data" %>

4. <%@ Import namespace = "System.Configuration" %>

5. <%@ Import namespace = "System.Web" %>

6. <%@ Import namespace = "System.Web.Security" %>

7. <%@ Import namespace = "System.Web.UI" %>

8. <%@ Import namespace = "System.Web.UI.WebControls" %>

9. <%@ Import namespace = "System.Web.UI.WebControls.WebParts" %>

10. <%@ Import namespace = "System.Web.UI.HtmlControls" %>

11. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

12. "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

Inline Encoding of the ASP.NET Page Example

Page 66: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

13. <script runat="server">

14.

15. protected void Page_Load(object sender, EventArgs e)

16. {

17. // display the server's current time in timeLabel

18. timeLabel.Text = String.Format( "{0:D2}:{1:D2}:{2:D2}",

19. DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second );

20. }

21. </script>

22. <html xmlns="http://www.w3.org/1999/xhtml" >

23. <head id="Head1" runat="server">

24. <meta http-equiv="Refresh" content="5; url=WebTime2.aspx" />

25. <title>A Simple Web Form Example</title>

26. </head>

Page 67: Web-Based Applications Using ASP.NET Dr. Awad Khalil Computer Science & Engineering Department AUC.

27. <body>

28. <form id="form1" runat="server">

29. <div>

30. <h2>Current time on the Web server:</h2>

31. <p>

32. <asp:Label ID="timeLabel" runat="server" BackColor="Black"

33. Font-Size="XX-Large" ForeColor="Yellow"

34. EnableViewState="False"></asp:Label>

35. </p>

36. </div>

37. </form>

38. </body>

39. </html>