ch12-cbs

advertisement
Chapter 12
Introduction to
ASP.NET

.NET is a collection of technologies
Run time environment
 Library
 Programming languages





A component is a piece of software that can used by
other components
A component has an interface that specifies how it
can be used without necessarily exposing the
implementation
Microsoft’s component system was named COM
(Component Object Model)
.NET is a framework for developing and deploying
software



Software consists of components
These components can reside on multiple systems
These components can be programmed in different
languages

.NET initially included five languages
Visual Basic .NET
 Managed C++ .NET
 JScript.NET (similar to JavaScript)
 J#.NET (Similar to Java)
 C#.NET (A new language in the C/C++/Java
family)


Other languages have been added

Including COBOL, Eiffel, Fortran, Perl, Python


CLR
Services for processing and executing .NET
software no matter what language






Garbage collection
Type checking
Debugging
Exception handling
Compilers translate a .NET language in
Intermediate Language (IL)
The runtime system compiles IL on the fly to
native machine code and executes that code

The IL is not interpreted directly

Two components
Common Type System (CTS)
 Common Language Specification (CLS)






CTS defines types supported by .NET
languages
Each type has a specified representation
Integer types, for example, includes Int32 (32bit signed integers)
.NET languages map their types into the CTS
types
Two categories of CTS types


Value types
Reference types (an address of a memory location)


Defines characteristics that languages must
have to properly interoperate with other
languages in the .NET framework
Include requirements and restrictions





No operator overloading
No pointers
Identifiers not case sensitive
The C# language violates the listed restrictions
The Framework Class Library (FCL) is a
collections of classes providing resources for
software








Designed as part of .NET
Object-oriented
Has many similarities with Java
Single inheritance, interfaces, garbage
collection, no global variables or methods
Pointers, operator overloading, preprocessor
Properties
Delegates
Indexes, attributes, events

Unsigned integer types (only positive whole
numbers)


Signed integer types (positive and negative
whole numbers)




sbyte, short, int, long
Floating point types


byte, ushort, uint, ulong
float, double
bool
decimal
char


Array, ArrayList, Queue, Stack defined by the
.NET FCL (Framework Class Library)
Array is a class, but syntax is like C/C++/Java



int[] a = new int[100]
Length property gives number of elements in the
array
Enumeration type



Value type
Finite set of values defined by the programmer
Type safe



The standard control statements of
C/C++/Java are in C# as well
foreach is added to step through a collection
foreach (type identifier in
collection) …
The switch statement is almost the same
except the syntax requires either a break or a
goto at the end of each case



C# has no methods or variables outside of classes
Syntax of class definitions, variable declarations and
function definitions similar to Java
Parameters may be passed in any of three modes





Pass by value (in)
Pass by reference (in-out)
Pass by result (out)
A method may take a single formal parameter that is an
array notated by the keyword params. This allows the
method to be called with a variable number of parameters
of the type of the elements of the array
Overriding methods requires


Marking the overridden method with virtual
Marking the overriding method with override

A C# struct is a lightweight class
No inheritance
 Can have constructors



Struct type objects are value types rather than
reference types
C# primitive types are implemented as
structs




A property of a class acts as if it were an
instance variable
However, assignment to the property actually
invokes a ‘set’ method associated with the
property
Access to the property invokes a ‘get’ method
Either method may be omitted


If the set method is omitted, assignments to the
property are not allowed
Methods may perform whatever checks or
calculations are needed




A delegate is a pointer to a method
Methods may be subscribed to a delegate
A delegate declaration specifies the protocol,
or the signature, of methods that may be
subscribed to the delegate
Methods subscribed to the delegate may be
called through the delegate


The FCL is divided into numerous namespaces
The most important namespace is System






Input and output
String manipulation
Event handling
Threading
Collections
System.Console is used for input and output to the
console




ReadLine
WriteLine
The using statement allows reference to members of a
namespace without qualifying the references
The main method of a program is Main


Does not require parameters
May return int or void

Multiple classes can be defined in a single
source file






Each class may have a Main method
In that case, running a program must specify which
Main is to start
Source file names do not have to match the class
name
Visual Studio is the usual vehicle for developing
.NET programs
Programs can, however, be developed with any
text editor
The stackClass.cs file defines two classes



Active Server Pages
Building dynamic web documents
The predecessor, ASP, embedded interpreted scripting
languages in XHTML



ASP.NET is similar



This approach has performance problems
It is difficult to divide up the development to different skill sets
The embedded languages allowed are the .NET languages
All code is compiled
ASP.NET documents extend the System.Web.UI.Page
class



Request and Response objects
HTMLControls, WebControls
IsPostBack


The Write method in Response sends output
to the response document
IsPostBack tells whether the current process
is the original request for the page or a
subsequent request with information from
the initial page


Code for ASP may be moved to a codebehind class
The ASP document itself will extend the
code-behind class rather than
System.Web.UI.Page

Documents can include
XHTML
 Directives
 Render Blocks Programming code in script
elements



Program code in script elements


Cannot define subprograms
Declare variables, define methods
Server side comments

<%-- …--%>


Directive names begin with @
Directives appear in <% … %> but the @
usually is attached to the <%:
<%@ directive-name attributes %>

@Page is required

Language attribute required: specifies .NET
language used for program code


Use Response.Write method
Takes a string parameter


Include markup since the target is an XHTML
document
The string.Format method can be used
to format output


The ex1.aspx example creates an array of random
numbers and displays them in the response page
An object of class Random is created to generate numbers






Method Next generates the next number
None or one or two parameters
Two parameter form used, result is in range n…m-1
A script element in the header declares three variables and
defines a method
The render block in the body references these definitions
and creates the dynamic part of the response
Static XHTML is sent as part of the response unchanged
ex1.aspx



The example ex2 has two files, ex2.aspx and
ex2.aspx.cs
This partitions the declaration code into a C#
file
The @Page directive includes two new
attributes



Inherits: value is the class name in the code-behind
file
Src: value is the name of the code-behind file
The Src attribute can be omitted if a compiled
version of the file is available in a bin subdirectory
ex2.aspx



XHTML elements associated with program
code
The code is executed on the server
Two categories
HTML controls
 Web controls





HTML controls are based on elements of XHTML
pages
The appearance and functionality of these elements
can be changed as the server executes
Executable code can be associated with the controls
Certain controls can raise events



ServerClick: control was clicked
ServerChange: control content was changed
HTML elements become HTML controls if


They are on the list associated with controls (Table 12.2)
The runat attribute has the value “server”



Note the runat attribute in the following XHTML:
<form runat=“server”>
<input type=“text” id=“address”
runat=“server”/>
</form>
There is a corresponding instance variable in the code
generated from this
protected HtmlInputText address;
There is no action attribute in the form: the ASP
document defines the actions that result from
submitting the form


Controls are represented as objects in the code
generated from ASP
Control classes inherit from HtmlControl
deriving properties and methods



Attributes property provides tag attributes as
name/value pairs
The Href property is defined by the HtmlAnchor
class
An XHTML tag can be designated as an HTML
control by simply adding the runat attribute
with the value “server”


An ASP.NET document can describe both a form and the response
Two kinds of requests to a ASP.NET document





Initial request
Request with form filled in, called a postback (a/k/a self-submitting form)
The IsPostBack property is true if the request is a postback request
In a postback, the Value propety of a control provides the data entered
into the corresponding widget
The state of a document is stored in the response after the initial service



A hidden control named ViewState contains a reference to a StateBag
object
The StateBag object stores data about the state of the document
This requires extra information to be exchanged between browser and server







A request is received
A document object is created and initialized
ViewState is initialized
The document is sent
The client sends a request back
A document object is created and initialized with
form data, including ViewState
Form data is used to update the state of the document
object
ViewState is updated


The program can directly set name/value pairs in
ViewState before this point
A response is returned


Clicking a submit button will cause a
postback
If the AutoPostBack property is set to
true, a postback will occur when a change is
made to a control

Two levels of events raised during processing


Control events (ServerClick, Server Change)
Page-level events
Init: after document class instantiated
 Load: after state set from form data
 PreRender: before instance is executed
 Unload: before instance is discarded


Implementing page-level event handling

Controlled by AutoEventWireup, default true



Which means use predefined method name by default
Implement predefined method names
(Page_unload, Page_load, …)
Override the virtual handlers

Two ways to register event handlers




Assign method names to attributes OnServerClick and/or
OnServerChange
Use delegates
Using attributes, the methods have predetermined
signatures
Using delegates




Event handler written with proper signature
New instance of delegate type created using the event
handler
Delegate subscribed to the event property of a control
This is often done in the Page_Init handler so it is done
one time as the page class is instantiated




Web controls are based on the controls from
Visual Basic
Namespace System.Web.UI.WebControls
Web controls do not match up directly with
HTML form widgets
An example of including a control in a page
<asp:textbox id=“phone”
runat=“server”/>



Panel organizes other controls
AdRotator produces different content on
different requests
ListControl has four subclasses
DropDownList
 ListBox
 CheckBoxList
 RadioButtonList



A control can be created with <asp:button…. in
the document
The same control can be created by
instantiating the Button class and assigning
values to properties of the object





.Text for the button label
.id for the id attribute
.OnClick for the handler
.runat to specify this as a web control
A asp:placeholder tag can be used to define a
place for controls defined in code

Those controls are added to the place holder


Response.Write does not place text properly
when intermixed with controls
Using a label is an alternative in order to
place text
<asp:label id="output”
runat="server"/>

This can be filled in later in the code
<% string msg = string.Format(
"The result is {0} <br />", result);
output.Text = msg; %>


The ex4.aspx example creates a number of
controls and creates a response
File ex4.aspx.cs is the code-behind file
ex4.aspx
ex4.aspx.cs

Validation controls validate data entered from other controls



These controls are placed immediately after the control whose
input is being validated
Four common validation controls





Server side validation is an important component of security
RequiredFieldValidator
CompareValidator
RangeValidator
RegularExpresionValidator
Example ex5.aspsx illustrates three of these



One field is required
One field (a phone number) must match a regular expression
pattern
One field must be in a specific range of values


“A collection of one or more related methods
that can be called by remote systems”
.NET provides support for constructing and
advertising web services

A document with extension .asmx is created





This may simply have a WebService directive
spcifying a codebehind file
The web service is implemented as a class that
extends System.Web.Services.WebService
The web service should be place in a developer
defined namespace in order to avoid conflicts
Some methods of the class will be tagged with
[WebMethod] to indicate that they are available
as part of the web service
Once a service is published, aspects of it can be
viewed using Internet Explorer

Two approaches to making a web service
known to potential clients
A web services discovery document
 A web services directory written with UDDI

Download