Web Forms and ASP.NET

acceptableseashoreSecurity

Nov 5, 2013 (3 years and 7 months ago)

69 views

Object Oriented Programming


Web forms, web controls
and ASP.NET

Dr. Mike Spann

m.spann@bham.ac.uk

Contents


Introduction


Static and dynamic web pages


How ASP.NET works


Introduction to web form programming


Visual Web Developer


Validation controls


Summary

Static and dynamic web pages


We are all familiar with the concept of
clients and web servers


Clients issue requests (using the
http

protocol) to web servers for web pages


The server responds with a message packet
containing
html

which is the encoded web
page


The web browser program running on the
client parses the
html

and displays the web
page

Static and dynamic web pages

Internet

Client

Server

http

GET request

http

response plus
html document

Static and dynamic web pages


Static web pages appear the same in response to
every request from the client to server


This is typical of simple
html

web pages


Dynamic pages can change depending on data
supplied from the client (so called
postback data
)
or be personalised for the user based on cookies
which are installed on the client computer


There are many technologies which support this
of which ASP.NET is a powerful Microsoft
example


Essentially it involves running asp scripts
supported by code written in a high level
language (typically VB or C#) on the server on
which .NET has been installed

Static and dynamic web pages


For example, we can create a static web
page to display times of movies as a cinema


www.eee.bham.ac.uk/spannm/MovieSite.
html


The problem with this is that the
information cannot be updated without
altering the
html code


html

consists of tags followed by text


The text is interpreted according to the
enclosing tags by the web browser


Static and dynamic web pages

<html>

<body background="James Bond1.jpg">


<TITLE>Movie Magic Cinema</TITLE>


<H1 align="
center
">


<FONT
color
="blue" size="7">


Welcome to a James Bond evening


</FONT>


</H1>


<P align="left">


<FONT
color
="lime" size="5">


<STRONG>


<U>
Showtimes

for Wed 10/31</U>


</STRONG>


</FONT>


</P>


<FONT size="5"
color
="yellow">


<P>The Man With The Golden Gun 1:05 pm, 3:25 pm, 7:00 pm</P>


<P>Diamonds Are Forever 12:50 pm, 3:25 pm, 6:55 pm</P>


<P>The World Is Not Enough 3:30 pm, 8:35 pm</P>


<P>From Russia With Love 12:45 pm, 6:45 pm</P>


</FONT>

</body>

</html>

Static and dynamic web pages


We can modify our static web page to include some
dynamic content


It will display the current date/time along with the
movie schedule


We will use ASP.NET to run server side code


http://www.eee.bham.ac.uk/spannm/ASP Net
stuff/
MovieSite
/MovieSite.aspx



The site will be an .
aspx

file which will look similar to our
original .
html

file


It will call methods from a C# class which is in a
code
behind

file


We will explain later how this all fits together

Static and dynamic web pages

<%@ Page Language="C#"
AutoEventWireup
="true"
CodeFile
="
MovieSite.aspx.cs
"
Inherits="
MoviePage
" %>


<!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>Movie Magic Cinema</title>

</head>

<body background="James Bond1.jpg">



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




<div>




<h1 align="center">




<font color="blue" size="7">





Welcome to a James Bond evening




</font>



</h1>



<p align="left">



<font color="lime" size="5">




<strong>




<U>
Showtimes

for <%
WriteDate
();%></U>




</strong>



</font>



</p>



<font size="5" color="yellow">



<%
WriteMovies
();%>



</font>




</div>


</form>

</body>

</html>

Static and dynamic web pages

using System;

using
System.Data
;

using
System.Configuration
;

using
System.Web
;

using
System.Web.Security
;

using
System.Web.UI
;

using
System.Web.UI.WebControls
;

using
System.Web.UI.WebControls.WebParts
;

using
System.Web.UI.HtmlControls
;


public partial class
MoviePage

:
System.Web.UI.Page


{



protected void
WriteDate
()



{



this.Response.Write
(
DateTime.Now.ToString
());



}




protected void
WriteMovies
()



{



this.Response.Write
(




"<P>The Man With The Golden Gun 1:05 pm, 3:25 pm, 7:00 pm pm</P>");



this.Response.Write
(




"<P>Diamonds Are Forever 12:50 pm, 3:25 pm, 6:55 pm</P>");



this.Response.Write
(




"<P>The World Is Not Enough 3:30 pm, 8:35 pm</P>");



this.Response.Write
(




"<P>From Russia With Love 12:45 pm, 6:45 pm</P>");


}

}


How ASP.NET works



To create a dynamic web page, we create an
.
aspx

file


If the client requests an .
aspx

file, because of
the file extension, the file is forwarded to
ASP.NET by the web server


ASP.NET parses the
.
aspx

file


It understands
.html
tags as well as ASP

tags
(<% and %>)


Ultimately ASP.NET will create an object,
using the code in the
.
aspx

file and the
codebehind (C#) file which produces the .
html

to send back to the client

How ASP.NET works

.aspx
file

.cs file

Web server

ASP.NET

Page derived
managed object

How ASP.NET works

Web server

ASP.NET

Page derived
managed object

html

html

To client

How ASP.NET works


From the 2 files, ASP.NET produces code for 2 files


The class is derived from the
System.Web.UI.Page

class
(which contains basic functionality to produce
html
)


Also
System.Web.UI.Page

contains functionality to
parse the request from the client including attached
postback

data


ASP.NET creates an instance of this object to
represent the page


How ASP.NET works


The real power of ASP.NET is that the production
of
html

is abstracted away to managed
components


For example, a button on a web form knows
how to produce the
html

to render itself on the
web page


All these components exist in the namespace
System.Web.UI.WebControls


It’s state may depend on
postback

data from the
client so the component may need to re
-
render
itself in response

How ASP.NET works

Browser

-

Client

Web server

ASP.NET

Browser client

Internet

Managed code

html

Browser request

and postback

data

Page

derived
and custom
objects

How ASP.NET works


In our simple example, code for a derived class of the
MoviePage

class is produced


An object is instantiated containing code for
method calls to
WriteDate
()

and
WriteMovies
()


More realistically our page will contain
web controls

which represent user interface elements on our web
page


These are defined in the FCL


We can design a web page using visual
programming techniques to drag and drop these
controls into our page


We don’t have to worry about producing the right
html
to send back to our browser

How ASP.NET works


Another key feature of ASP.NET is its runtime
performance


ASP.NET parses the .
aspx

files at runtime


Code is compiled into binary assemblies (.
dll

files) which are cached and reused


A web form application must only be parsed
once after each modification to source files


On receiving a request from the client,
ASP.NET looks for an already compiled
assembly to fulfil the request otherwise it
creates one from the submitted
.
aspx

file and
code
-
behind file


Introduction to web form
programming



Web form programming allows us to insert web
controls (for example buttons, labels, images etc)
into web pages


We can do this programmatically in the
.
aspx

and
codebehind files


Or we can do this using the design view in Visual
Studio


It allows us to design interactive
webpages

whose
visual representation changes in response to user
interaction

Introduction to web form
programming

Control

Description

AdRotator

Implements a rotating banner add.

Button

Implements a button for web user interface.

Calendar

Implements a highly configurable calendar UI.

CheckBox

Implements a check box for web UI.

DataGrid

Implements a table that supports automatic binding to data sources.

HyperLink

Implements a dynamic hyperlink.

Image

Implements an image for inclusion in web UI.

Label

Implements a dynamic label or text output.

LinkButton

Implements a hyperlink style button.

ListControl

Implements a list box for web UI.

Panel

A virtual control that is a collection of controls. This control is useful for
treating a block of controls as a single entity. For example, it is easy to
create a
Panel

to cause blocks of controls to appear or disappear from
the rendered HTML.

Table

Implements a simple table with custom rows and cells.

TextBox

Implements an editable text box for web UI.

RangeValidator

Implements a
validator

that assures that an entry in another control on the
page falls within a given range.
Validator

controls automatically generate
client
-
side script to perform validation for browsers that support
JScript
.
Whether or not validation is performed on the client side, validation is also
performed on the server side by the control.

RequiredFieldValidator

Implements a
validator

that assures that an entry was made to a field.

Introduction to web form
programming


As a simple example, the following website
allows the month’s calendar to be displayed
for any user inputted date


It demonstrates the use of the button,
label, textbox and calendar web controls


http://www.eee.bham.ac.uk/spannm/Web
Controls.aspx

Introduction to web form
programming

<%@ Page Language="C#"
AutoEventWireup
="true"
CodeFile
="
WebControls.aspx.cs
"
Inherits="
DatePage
" %>


<!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>Demonstrating simple web controls</title>

</head>

<body
bgColor
="orange">



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



<p align="left">



<font color="white">




Enter a Date Here<
br
>




<
asp:TextBox

id="date"
runat
="server"/><
br
>




<
asp:Button

id="button"




Text="Then press this button"




runat
="server
“/ >



</font>



</p>



<p align="left">



<
asp:Calendar

id="calendar" Visible="false"
runat
="server“/>

</p>



</form>

</body>

</html>

Introduction to web form
programming

using System;

using
System.Web.UI
;

using
System.Web.UI.WebControls
;


public partial class
DatePage

:
System.Web.UI.Page


{



protected void
Page_Load
(object sender,
EventArgs

e)



{



button.Click

+= new
EventHandler
(
OnButtonClicked
);



}




protected void
OnButtonClicked
(Object sender,
EventArgs

args
)



{



String
dateString

=
date.Text
;



try



{



DateTime

enteredDate

=
Convert.ToDateTime
(
dateString
);



calendar.SelectedDate

=
enteredDate
;



calendar.VisibleDate

=
enteredDate
;



calendar.Visible

= true;



}



catch (
FormatException
)



{



calendar.Visible

= false;



}



}

}

Introduction to web form
programming


The <
asp:>
tag in the
.
aspx

file indicates that we
are defining a web control


asp:

is shorthand for the
System.Web.UI.WebControls

namespace


The
runat
=“server”

attribute for each web
control indicates that these controls are to be
implemented on the server side


We are setting the properties of our web control
objects in the
<asp: >

but we could also use
the properties window in Visual Studio


Visual Web Developer



A sub
-
set of Visual Studio is the Visual
Web Developer which has a visual designer
based on Front Page


Allows the developer to use ‘drag and
drop’ to insert web controls into web
pages


Code can then easily be added to the
codebehind files


Typically this would be event handler
functions for the controls

Visual Web Developer


We select File
-
>New
-
>Web site and then select ASP.NET
Web Site


Normally HTTP is selected and the location (in this
case
http://localhost/xxxx

means under the local

wwwroot
’ directory (assuming IIS has been installed
locally)

Visual Web Developer


Web Developer has a design mode rather similar to the
design mode we used to create GUI’s in normal windows
programming


It differs slightly in that there is a cursor position and any
web controls or text are added at the current cursor
position


The
.
aspx

file is updated as the web site is created in
design mode


The currently designed website can be previewed at any
time


As in normal windows program development, the event
handler code for web controls (
eg

buttons) have to be
added by the developer


Visual Web Developer


We can create the web page for displaying the
calendar using design mode


The label, text field, button and calendar are
inserted into the page using drag and drop


We set the visible property of the calendar to
false in its properties window


We set the background colour of the outer form
using the properties
windon


All code except the
Page_Load
()

and
Button_Click
()
methods is automatically created

Visual Web Designer Demo


Validation controls



A validation control determines whether the data
entered in a web control is in the proper format


For example a postcode entered in the correct
alphanumeric format


A date entered in the correct
dd
/mm/
yyyy

format


A correct email address is entered


etc


The validation check is carried out by the client by
converting the
validator

to
Javascript

to perform
the validation before submitting the data to the
server



Validation controls


Validation controls can be input onto a webpage using
Visual Web Developer


Actual validators for things like phone numbers, email
addresses are defined by
regular expressions


These are strings containing formatting characters
used to match to particular patterns in text


We can define our own regular expressions as
validators for particular inputs


Luckily however, Visual Web Developer has a
regular Expression Editor

dialog box allowing us to
choose standard regular expressions for things like
email addresses and phone numbers


Demo

Validation controls


For example we can create a simple web form to
input a name, email address and phone number
into textboxes and include input validators for
each


We can also make each input a
required field

so
that each field must be input before submitting
to the server


We also include a label at the bottom of the form
for the server response


The
visible

property of this label is initially set
to false


Validation controls


We can add required field validators to each of our
input textboxes


We can set the
ControlToValidate

and
ErrorMessage

properties in the properties
window of each validation control


The validation controls remain invisible in the
website unless an input is not added before the
form is submitted


The required error message is displayed


The form is not submitted to the server

Validation controls


Next we can add
RegularExpression

validators to
our input text boxes for email and phone numbers


We can use a standard regular expression for
email taken from the dialog which is obtained
from the properties window


\
w+([
-
+.']
\
w+)*@
\
w+([
-
.]
\
w+)*
\
.
\
w+([
-
.]
\
w+)*


We can generate our own for a UK phone
number


((
\
(
\
+
\
d{2}
\
) ?)|(
\
+
\
d{2}
-
))?
\
d{3}
-
\
d{3}
-
\
d{4}


eg

(+44)(121
-
414
-
4329)

<%@ Page Language="C#"
AutoEventWireup
="true"
CodeFile
="
Validation.aspx.cs
" Inherits="Validation" %>


<!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>Demonstrating Validation Controls</title>

</head>

<body
bgcolor
="#ffcc99">


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



<div>




Please fill out the following form<
br

/><
br

/>




<strong>All fields are required and must be in the valid format</strong><
br

/><
br

/><
br

/>



<
asp:Label

ID="Label1"
runat
="server" Font
-
Bold="True" Text="Name:"></
asp:Label
>



&
nbsp
; &
nbsp
;



<
asp:TextBox

ID="TextBox1"
runat
="server"></
asp:TextBox
>



<
asp:RequiredFieldValidator

ID="RequiredFieldValidator1"
runat
="server"
ErrorMessage
="Please enter your name"

ControlToValidate
="TextBox1" Display="Dynamic"
ForeColor
="Blue"></
asp:RequiredFieldValidator
><
br

/><
br

/>



<
asp:Label

ID="Label2"
runat
="server" Font
-
Bold="True" Text="E
-
mail address:"></
asp:Label
>



&
nbsp
;&
nbsp
;



<
asp:TextBox

ID="TextBox2"
runat
="server"></
asp:TextBox
>



&
nbsp
;&
nbsp
;



<asp:Label ID="Label3" runat="server" Text="e.g.user@domain.com"></asp:Label><br />



<
asp:RequiredFieldValidator

ID="RequiredFieldValidator2"
runat
="server"
ControlToValidate
="TextBox2"


ErrorMessage
="Please enter your email address"
ForeColor
="Blue"></
asp:RequiredFieldValidator
>&
nbsp
;



<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox2"


Display="Dynamic"
ErrorMessage
="Please input your email address in the correct format"


ForeColor
="Blue"
ValidationExpression
="
\
w+([
-
+.']
\
w+)*@
\
w+([
-
.]
\
w+)*
\
.
\
w+([
-
.]
\
w+)*">

</
asp:RegularExpressionValidator
><
br

/>



<
asp:Label

ID="Label4"
runat
="server" Font
-
Bold="True" Text="Phone number:"></
asp:Label
>



&
nbsp
; &
nbsp
;&
nbsp
;



<
asp:TextBox

ID="TextBox3"
runat
="server"></
asp:TextBox
>



<
asp:Label

ID="Label5"
runat
="server" Text="e.g.(+44) 121
-
414
-
4324"></
asp:Label
><
br

/>



<
asp:RequiredFieldValidator

ID="RequiredFieldValidator3"
runat
="server"
ControlToValidate
="TextBox3"


Display="Dynamic"
ErrorMessage
="Please enter your
telphone

number"ForeColor
="Blue">

</
asp:RequiredFieldValidator
>



<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="TextBox3"


Display="Dynamic"
ErrorMessage
="Please enter a phone number in valid format"


ForeColor
="Blue"
ValidationExpression
="((
\
(
\
+
\
d{2}
\
) ?)|(
\
+
\
d{2}
-
))?
\
d{3}
-
\
d{3}
-
\
d{4}">

</
asp:RegularExpressionValidator
><
br

/>



<
asp:Button

ID="Button1"
runat
="server" Height="37px" Text="Submit" Width="132px" /><
br

/><
br

/>



<
asp:Label

ID="Label6"
runat
="server" Text="Thank you for filling out this form"


Visible="False" Font
-
Italic
="False"> </
asp:Label
></
div
>


</form>

</body>

</html>

Validation controls


Its often useful to display the data that was
submitted on the same web form


In practice, this data would be stored on file or
in a database


We can do this using a
postback

event


A
postback

event is raised in response to the
client
-
side button click and causes the page to
be loaded by ASP.NET at the server a second
time


The
IsPostBack

property of
Page

is set to
true if the page is re
-
loaded in response to a
postback

Validation controls

using
System.Configuration
;

using
System.Web
;

using
System.Web.Security
;

using
System.Web.UI
;

using
System.Web.UI.WebControls
;

using
System.Web.UI.WebControls.WebParts
;

using
System.Web.UI.HtmlControls
;


public partial class Validation :
System.Web.UI.Page


{


protected void
Page_Load
(object sender,
EventArgs

e)


{


if (
IsPostBack
)


{


string name =
Request.Form
["TextBox1"];


string email=
Request.Form
["TextBox2"];


string phone=
Request.Form
["TextBox3"];


Label6.Text += "<
br
><
br
>";


Label6.Text+="You have inputted the following <
br
>";


Label6.Text+="Name: " + name +"<
br
>";


Label6.Text+="Email address: " + email +"<
br
>";


Label6.Text+="Phone number: " + phone +"<
br
>";


Label6.Visible = true;


}


}

}

Validation controls


http://
www.eee.bham.ac.uk/spannm/ASP NET
stuff/
ValidationControls
/Validation.aspx


Summary


We have looked at the difference between static and
dynamic web pages and how we can generate simple
dynamic web pages


We have looked at how ASP.NET generates dynamic
objects at the web server from
.
aspx

files and C#
codebehind

files


We have looked at simple web form programming


We have looked at the use of Visual Web Designer to
build dynamic websites


We have looked at how we can build in validation controls
to our websites