Chapter 5
Programming the Web
Server-side Programming
ASP .NET Web Forms
Yingcai Xiao
Programming the Internet
The Internet as a Computer
Every computer on the Internet is a “CPU”
Transmitting the data over the Internet is the Key
Analogy of Internet Protocols:
IP (Internet Protocol)
=> “Binary” (low-level Internet transmission protocol)
HTTP (Hyper Text Transport Protocol)
=> “Intermediate Language” (high-level Internet transmission protocol)
HTML (Hyper Text Markup Language)
=> High Level Language (for writing web-pages in)
Internet Protocol
IP: Internet Protocol:
The data transmission protocol (standard) for the Internet.
DARPA Vint Cerf and Bob Kahn in 1974
The Internet is a computer network based on the Internet Protocol.
Each device on the Internet is identified by its Internet Address: or
Data transmitted between computers as packets.
Each packet has an IP header followed by data.
The first 2 entries in an IP header are the receiver’s address and the sender’s
address. IP is similar to postal mailing (Packet Switching), not phoning
(Circuit Switching).
Routers/Gateways forward packets based on network topology and traffic.
IPv4 (32bit addressing, 4B), IPv6 (48bit addressing, 256T)
The headers are in the standard IP format, platform-independent.
Data (any type) is transmitted over the Internet bit-by-bit. No restrictions on
what can be transmitted.
Internet Protocol
More on IP
Any IP device can join and drop off the Internet at anytime. (Not so for
IBM’s token ring networks.)
Packets received may not in the order they were sent.
Wait and send again if network is busy. Transmission speed decreases as
traffic increases. DoS attacks.
Binary data are platform-dependent. Binary data transmitted from one
computer to another computer may not be readable by the receiver if it has a
different binary data format than the sender.
Hypertext Transfer Protocol
Can we make the data platform-independent?
The World Wide Web is an application built on the Internet using the Hypertext
Transfer Protocol in which only text data is permitted to be transmitted.
HTTP (Hypertext Transfer Protocol)
• Tim Berners-Lee ("father of the Web") and RFC 2068
( 1989.
• Entirely text based: ASCII (8-bits) or Unicode (16-bits).
• Platform independent
• Defines how Web browsers and Web servers communicate.
• 7 instructions defined in HTTP 1.1.: GET, POST, …
• Transmitted over TCP/IP (Transport Control Protocol/Internet Protocol).
• Web applications are implemented over the Internet using HTML and other
Web languages.
Internet Browser
GET HTML pages from servers
Display the HTML pages at the clients.
• Tim Berners-Lee: The first web browser, 1990, was called
• Robert Cailliau: Erwise, the first commonly available web browser
with a graphical user interface.
• Marc Andreessen: Mosaic, the first popular browser, 1993, Netscape
• Google: Chrome, the most used browser currently (51% 01/2015),
HTML (Hypertext Markup Language)
Defines syntax and semantics of the Web language.
Entirely text based (platform independent)
Hypertexts are tagged in < >, not to be displayed. They are
metadata describing regular text.
Browsers are GUI-based HTML interpreters.
HTML 4.01 became XHTML 1.0 in 2000
Hello, world
Computing over the Internet
 Client-Side:
• Thin client
1. Only a browser is needed.
2. The browser renders a html page on the client
3. HTML (static), DHTML (dynamic), HTML5 (dynamic
and multi-medium).
4. Programming with embedded scripts: JavaScript, .
Dynamic and computational.
5. Ajax (asynchronous JavaScript & XML):
6. Plugins: VRML (3D Web)
7. Java Applet: transmit the application to the client and
run it there. Too much to transmit for large distribution
Computing over the Internet
 Client-Side:
• Thick client
1. Client program installed prior, no need to download at
2. Runs like any other program on the client, but can talk
to the server when needed.
3. .NET Remoting, Windows Communication Foundation
4. Java's Remote Method Invocation (RMI)
5. Common Object Request Broker Architecture
Computing over the Internet
 Server-Side:
• Web pages are generated by server side programs at
runtime. Dynamic contents and heavy-duty computing.
• Server Scripts
1. Perl, PHP, ….
2. Does not scale well. (each client needs a process to
• Server VMs
1. .NET ASP (Active Server Page), JSP (Java Server
2. All clients are served by a single process. The process
will create a thread to serve each client.
Computing over the Internet
 Server-Side:
• CMS (Content Management Systems): web contents are
managed at server side on demand.
• Dejango CMS, Joomla.
 Server-Client Communication:
• Important for Internet based computing.
• HTTP channel (slower, works for both thin and thick
• TCP/IP channel (faster, works only for thick clients).
• HTTP next, TCP/IP later.
What happens when browsing a web page on a server?
Start a client (a browser).
Type in the URL (Unified Resource Locator).
Internet’s Domain Name System (DNS) converts into an IP address (
The browser opens a socket (IP) connection to the server
using default port 80
What happens when browsing a web page on a server?
The browser transmits an HTTP request to the server.
GET /xiaotest/calc.html HTTP/1.1
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-agent: Mozilla/4.0.(compatible; MSIE.6.0; Windows NT 5.1)
Connection: Keep-Alive
[blank line]
What happens when browsing a web page on a server?
The server software (e.g. IIS, Tomcat) processes client
requests from the designated port (80 by default).
•Locates the file under the server’s web root directory
•Returns “Server Error 404” if file not found.
•Otherwise returns the contents of the file as text to the
client with a text header.
What happens when browsing a web page on a server?
The server transmits an HTTP response back.
HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Date: Wed, 24 Oct 2014 14:12:37 GMT
Content-Type: text/html
Accept-Ranges: bytes
Last-Modified: Wed, 24 Oct 2014 14:00:53 GMT
ETag: "d02acf81975cc11:a78"
Content-Length: 4800
[blank line]
What happens when browsing a web page on a server?
• Upon receiving the response, the browser parses the
HTML and displays the resulting Web page.
• To compute, we need to get data from the client user.
• A client form is needed. HTML form serves the
HTML Forms
<form method=“post”>
<input type="text" name="op1" />
<input type="text" name="op2" />
<input type="submit" value=" = " />
What’s happening?
No action to send anything to the server when the user types values
in the text fields. But when the submit button (<input
type=“submit”>) is clicked, the browser submits the form along
with any input in the form’s controls.
POST /xiaotest/calc.html HTTP/1.1
Content-Length: 11
[blank line]
Server Side Processing
Web Server
 Weber server hardware hosts the web server software.
 Web server software listens to HTTP requests from the web port (80).
 It processes the requested pre-deployed web page.
 Deploying a Web Page on an IIS server.
IIS: Internet Information Services
Deploying Directory:
Access URL: http://localhost/ (case insensitive)
Web Server Software
Common Gateway Interface (CGI)
• CGI applications write HTTP responses to standard
output (stdout) on the server, which are then forwarded to
the client browser by the web server.
• CGI defines a low-level programmatic interface between
Web servers and applications that run on Web servers.
• CGI applications can be written in any programming
• CGI applications read the input accompanying postbacks
through server environment variables and standard input
• Slow, restarts a process on every request.
 ISAPI: Internet Server Application Programming Interface
ISAPI extensions are Windows DLLs hosted by IIS.
They’re referenced by URL just like HTML files (for
IIS forwards HTTP requests to an ISAPI DLL by calling a
special function exported from the DLL.
The DLL generates HTTP responses.
Faster than CGI (run in the same process as IIS).
Once loaded, they remain in memory.
They’re difficult to write.
Active Server Pages (ASP)
Active Server Pages (ASP)
Introduced in 1996.
Dynamically generates HTML on Web servers.
Allows HTML and scripts / languages to be mixed.
The embedded script code are between the <% and %> tags.
When an Active Server Page is requested, ASP server parses the
page and executes any scripts contained inside it.
Scripts access the input by using the Request object.
Scripts write HTML to the HTTP response using the Response
object, which is sent to the client by the Web server along with
the static HTML.
ASP integrates with ActiveX Data Objects (ADO).
Interpreted, slow.
Lacks encapsulation.
<%@ Language="VBScript" %>
<input type="text" name="op1" value="<%= Request ("op1") %>"/>
<input type="text" name="op2" value="<%= Request ("op2") %>" />
<input type="submit" value=" = " />
If Request ("op1") <> "" And Request ("op2") <> "" Then
a = CInt (Request ("op1"))
b = CInt (Request ("op2"))
Response.Write (CStr (a + b))
End If
Microfoft’s equivalent of JSP
Code on the server that dynamically generates HTML for the
clients at runtime.
 JSP: Java Server Page
Java code on the server that generates HTML for the clients.
HTML contents can be dynamically generated at runtime
ASP based on the .NET framework, one of the most popular
web programming techniques. Code on the server that
dynamically generates HTML for the clients at runtime.
Application 1
Application 2
Application 3
Web Forms
Web Forms are GUI-based EDP web pages built around controls and event
.NET web forms are processed on the server side.
Web forms use HTML, HTTP and IP to transmit and display GUI into a client
ASP.NET Web Forms
 ASP.NET Web Forms
GUI for Web applications
Object-oriented (encapsulation, inheritance, polymorphism)
Event driven (EDP)
Server-side processing (dynamic generation of HTML)
Compiled code, faster
HTML embedding tag: <asp: \>
(processed on the server side)
File extension: .aspx
To deploy on winserv1:
copy Examples/c5/calc.aspx to
To access:
<form RunAt="server">
<asp:TextBox ID="op1" RunAt="server" />
<asp:TextBox ID="op2" RunAt="server" />
<asp:Button Text=" = " OnClick="OnAdd" RunAt="server" />
<asp:Label ID="Sum" RunAt="server" />
<script language="C#" RunAt="server">
void OnAdd (Object sender, EventArgs e)
int a = Convert.ToInt32 (op1.Text);
int b = Convert.ToInt32 (op2.Text);
Sum.Text = (a + b).ToString ();
When Calc.aspx is accessed by a client
An ASP.NET server page contains two parts: static HTML
code and dynamic embedded APS.NET code.
ASP.NET-enabled web server processes the ASP.NET code in
the server page. (Tomcat does not support ASP.NET but
Mono does)
It instantiates TextBox, Button, and Label objects (the
classes are defined in System.Web.UI.WebControls).
Each object dynamically renders itself into HTML.
 The dynamically generated HTML is merged into the static
 The resulting HTML is returned to the client as an HTTP
Calc.aspx as seen by the client
<form name="_ctl0" method="post"
action="calc.aspx" id="_ctl0">
<input type="hidden" name="__VIEWSTATE"
value="dDwxOTE0NDY4ODE2Ozs+" />
<input name="op1" type="text" id="op1" />
<input name="op2" type="text" id="op2" />
<input type="submit" name="_ctl1" value=” = " />
<span id="Sum"></span>
note: there are also “hidden” and “div” (section) tags.
When Calc.aspx is accessed by a client
• When the “ = “ button is clicked, the input from “op1” and “op2”
are posted to the server and directed to calc.aspx (since
• On the server side, ASP.NET notifies the Button object in
calc.aspx and the Button responds by firing a Click event.
• ASP.NET receives the event and subsequently invokes its handler:
OnAdd ( ).
• “Sum.Text = (a + b).ToString ();” renders the result into the
“Sum” label in <span id="Sum"></span> as HTML.
• The dynamically generated HTML is merged with the static
HTML (parts not in server side tags).
• The resulting HTML is sent to the client browser.
Use the client browser’s View->Page Source menu to see the final
HTML code received by the client.
(Mac/Crome: View->Developer->View Page Source
ASP.NET Controls
 Two types: Web Controls and HTML Controls
 Web Controls
Class names are prefixed with asp:.
Classes are from System.Web.UI.WebControls.
The name of the object is defined by the ID attribute.
ASP Web controls are rendered into HTML.
ASP Web controls are highly programmable.
They support methods, properties, events.
<asp:TextBox Text="2" ID="op1" runat="server" />
This web control initializes the textbox to display 2. Any
public property of a control can be used this way.
ASP.NET Controls
Control properties can be accessed from server-side scripts (code
between the <script> and </script> tags).
Read a control property by scripts:
int a = Convert.ToInt32 (op1.Text);
Write a control property by scripts:
Sum.Text = (a + b).ToString ();
Event-driven programming. Controls fire events when users click
on them. Wiring an event to an event handler is accomplished by
prefixing the event name with “On”.
<asp:Button Text=" = " RunAt="server" OnClick="OnAdd" />
ASP.NET Controls
Exception handling can be added in the handlers.
void OnAdd (Object sender, EventArgs e)
{ try {
int a = Convert.ToInt32 (op1.Text);
int b = Convert.ToInt32 (op2.Text);
Sum.Text = (a + b).ToString ();
catch (FormatException) {
Sum.Text = “Format Error";
The Web Forms Programming Model
Three principles of the Web Forms programming model:
A Web form’s user interface is “declared” using a
combination of HTML and server controls.
Server controls fire events that can be handled by server-side
Server-side scripts in ASP.NET are compiled to CIL and
executed by the CLR on the server.
RunAt=“server” must be used in every tag that ASP.NET is to
Web Controls
Displays rotating banners in Web
Generates submit buttons
Displays a check box in a Web form
Validates user input using the
Displays calendars with selectable
Displays a group of check boxes
Validates user input by comparing it to
another value
algorithm of your choice
Web Controls
Displays data in tabular format
Displays items in single-column or
multicolumn lists using HTML
Generates HTML drop-down lists
Generates hyperlinks
Displays images in Web forms
Displays graphical push buttons
Generates programmable text fields
Generates hyperlinks that post back to
the server
Web Controls
Generates HTML list boxes
Generates literal text in a Web form
Groups other controls
Displays a radio button in a Web form
Displays a group of check boxes
Verifies that user input falls within a
specified range
Validates user input using regular
Displays items using HTML templates
Web Controls
Verifies that an input field isn’t empty
Generates HTML tables
Generates text input fields
Displays a summary of validation
Displays XML documents and
optionally formats them using XSLT
HTML Controls
 ASP.NET HTML controls mimic the original HTML tags.
(They are processed on the server side. They are not HTML tags
which are processed by the client browser.)
e.g. <input type="text" RunAt="server" />
HTML controls are used like HTML tags.
An HTML control is an instance of
ASP.NET sees the RunAt=“server” attribute and creates an
HtmlInputText object.
The HtmlInputText object, in turn, emits an <input
type=“text”> tag that’s ultimately returned to the browser.
HTML controls (server side) have properties and can
generate events which make them more powerful than
HTML tags (client side).
 Without RunAt="server“, HTML controls become HTML tags.
HTML Controls
Corresponding HTML Control
<a runat=“server”>
<button runat=“server”>
<form runat=“server”>
<img runat=“server”>
<input type=“button” runat=“server”> HtmlInputButton
<input type=“reset” runat=“server”>
<input type=“submit” runat=“server”> HtmlInputButton
HTML Controls
<input type=“checkbox”
<input type=“file” runat=“server”>
<input type=“hidden” runat=“server”> HtmlInputHidden
<input type=“image” runat=“server”>
<input type=“radio” runat=“server”>
<input type=“password”
<input type=“text” runat=“server”>
<select runat=“server”>
HTML Controls
<table runat=“server”>
<td runat=“server”>
<th runat=“server”>
<tr runat=“server”>
<textarea runat=“server”>
Any other tag with runat=“server”
The HTML controls version of Calc.aspx
<form runat="server">
<input type="text" id="op1" runat="server" />
<input type="text" id="op2" runat="server" />
<input type="submit" value=" = " OnServerClick="OnAdd" runat="server" />
<span id="Sum" runat="server" />
<script language="C#" runat="server">
void OnAdd (Object sender, EventArgs e)
{ int a = Convert.ToInt32 (op1.Value);
int b = Convert.ToInt32 (op2.Value);
Sum.InnerText = (a + b).ToString (); }
How does an ASP.NET enabled server process an ASPX file?
When ASP.NET processes the first HTTP request for an ASPX file:
1. It creates class representing the dynamic code of the file.
2. It compiles it, loads it, creates an object for it.
3. The object initializes itself and processes page-level events.
4. The object generates HTML output to be sent to the client.
5. The object remains in the server memory to process further
requests to the page.
6. When the ASPX file is modify, ASP.NET automatically repeats
steps 1-4.
How does a ASP.NET enabled server process an ASPX file?
When ASP.NET processes the first HTTP request for an ASPX file:
It creates a Page class deriving from class
It copies the code in the ASPX file to the Page-derived class.
A method (e.g. OnAdd) in a <script> block becomes a
member method of the derived class.
4. ASP.NET compiles the derived class and places the resulting
DLL in a system folder and caches it there.
\Temporary ASP.NET Files.
ASP.NET instantiates an object of the derived Page class
and “executes” it by calling a series of methods on it.
The Page object instantiates any controls declared inside it
and solicits their output.
Page-Level Events
As the Page object executes, it fires a series of events (page-level events) that
can be processed by server-side scripts:
 “Init”, which is fired when the page is first instantiated, and
 “Load”, which is fired after the page’s controls are initialized but before
the page renders any output.
Implicit wiring of Page events to handlers by defining handlers’ names
as Page_EventName.
<asp:DropDownList ID="MyList" RunAt="server" />
<script language="C#" runat="server">
void Page_Load (Object sender, EventArgs e)
{ if (!IsPostBack) { // if it is not from the client
for (int i=0; i<5; i++) {// list 5 days
DateTime date =
DateTime.Today + new TimeSpan (i, 0, 0, 0);
MyList.Items.Add (date.ToString ("MMMM dd, yyyy"));
} } } </script>
ASP.NET Compilation Directives @
Must be positioned at the top of an ASPX file.
@ Page
Defines general attributes and compilation settings for
ASPX files (e.g. Language)
@ Control
Defines general attributes and compilation settings for
ASCX files
@ Import
@ Assembly
@ Register
Imports a namespace
@ OutputCache
Exerts declarative control over page caching and
fragment caching
@ Reference
@ Implements
Adds a reference to an external ASPX or ASCX file
Enables linkage to assemblies, not linked to by default
Registers user controls and custom controls for use in a
Web form
Identifies an interface implemented by a Web page
Separating Static Code from Dynamic Code
1. ASPX files are in text files, anyone can read it.
2. When a company sells its ASPX server programs, it does not want
people to see their source code.
3. How? Code-behind is designed to protect the source code.
4. For the static code in HTML, we can’t do anything about it.
5. Dynamic code in C# or other .NET languages can be separated out
and compiled into DLLs.
6. Only the static HTML code and the DLLs are delivered to the
7. The dll can be written in any server-side compiled programming
Code-behind with C#
1. Create a CS file (e.g. Examples/C5/Lander/LanderCB.cs) containing
code that would normally appear between <script> and </script> tags.
Make each of these source code elements members of a class (e.g.
LanderCBPage) derived from System.Web.UI.Page.
2. In your Page-derived class, declare protected fields whose names
mirror the IDs of the controls declared in the ASPX file (e.g.
LanderCB.aspx). At run time, ASP.NET maps these fields to the
controls of the same name.
3. Compile the CS file into a DLL.
In a Visual Studio Command Prompt window, run the following:
csc /target:library LanderCB.cs
Code-behind in Web forms coded in C#
4. Place the HTML portion of the Web form—everything between
the <html> and </html> tags—in an ASPX file (e.g.
5. Include in the ASPX file an @ Page directive containing an
Inherits attribute that identifies the Page-derived class in the
DLL. When a request arrives for that page at run-time,
ASP.NET derives a child class from this class to create the form.
e.g. <%@ Page Inherits="LanderCBPage%>
7. Code embedded has to be in C#, VB .NET, or JScript. Codebehind can be in any other language supported by .NET.
Code-behind in Web forms coded in C#
8. To deploy the program:
move the ASPX file to Inetpub/wwwroot/xiaotest/ and
the DLL to Inetpub/wwwroot/xiaotest/bin.
9. The program can be accessed the same way as other
ASP.NET programs:
9. In order for
to work, the Lander directory has to be converted to a Web
Application, which instructs ASP.NET to find Lander.dll under
the application’s bin directory. (This is done for your home
directory on winserv1.)
To use the source code without recompiling:
<%@ Page Inherits="LanderPage" Src="Lander.cs" %>
Code-behind in Web forms coded in C#
To use the source code without recompiling during development:
Copy Lander.cs to LanderSRC.cs
Rename the class in it from LanderPage to LanderSRCPage
public class LanderSRCPage : Page
Copy LanderDLL.aspx to LanderSRC.aspx
Rename the class to inherit and add the source file.
<%@ Page Inherits="LanderSRCPage" Src="LanderSRC.cs" %>
You have to rename the class otherwise it would conflict the class
name in code behind and get an error
BC30456: 'InitializeCulture' is not a member of ...
Setting Up a Folder Web Access
 Right click on the folder in File Explorer, select Properties
 Select the Security Tab
 Edit -> Add
 IUSR (
 Give them the following permissions:
Read & execute
List folder content
In order to support Code Behind, a folder needs to be converted
into an Web Application, so that ASP.NET knows to find DLLs
in the its bin subfolder.
Create a Web Application in IIS
 winserv1 -> Sites -> Default Web Site
 Right-click->Add Application
 Alias: xiaotest
 Application pool: defualtAppPool
 Physical path: C:\inetpub\wwwroot\xiaotest\
 URL:
Existing directories can be converted to Web Applications
• winserv1 -> Sites -> Default Web Site->xiaotest
• Right-click on it
• Convert to Application
• Application pool: defualtAppPool
• URL:
* You need to be an administrator to use IIS
Web Forms and Visual Studio .NET
Development of Web forms using Visual Studio .NET
• Create a Web Application project
• Set the URL for publishing
• Use forms designer to design forms by drag-and-drop controls
from a palette onto the forms.
• Edit the HTML.
• Write event handlers by double-clicking controls and filling in
empty method bodies.
• Compile and run applications by executing simple menu
Web Programming, Client Side, Server Side, HTTP, HTML, HTML
Controls, IIS, Web Forms Programming Model, Page-Level Events,
Code Behind.
 Principles:
What are they?
How do they work? (internals, static structures, dynamic
data/event flow.)
 Practice:
Explain the logic, output, and internal working of a given
code segment.
Find errors in a given code segment.
Write a simple program to perform a given task.

Applet Graphical User Interface Event