Вы находитесь на странице: 1из 15

Topic 2 : Web Forms & Server Controls Part 1

What is a web form?


Contents HTML,Javascript,directives,server side scripts
Programming Models
Code inline model & Code behind (2-page) model
Code inline model put code in 1 page, separate section of file
(aspx only)
Code behind model Presentation code (aspx)
- Application logic (aspx.cs)
Page Directives
Codefile References the code-behind file in which the page is associated
(e.g. luckyNo1.aspx.cs)
Inherits luckyNo1 (class name)
Language C#
Form Control Types
HTML Controls
usual <input type=button value=Button name=B3>
HTML Server Controls
more powerful than HTML controls:
Allows use of ASP.NET event handlers
Allows your server side code(e.g.C#) to retrieve information
from the control easily
ASP.NET Web Controls
Similar function as for HTML server control
e.g. <asp:Button id=button1 Text=Click me runat=server
</asp:Button>
Must have two attributes
id(unique string to identify the control) & runat(must contain the value
server)
Differences between the 3
HTML Control Original, Client side process, CSS style
HTML Server Control HTML control move to Server side, Backward
compatible(runat) with HTML, Data persistent when going forward & back(as
compared with HTML control)
ASP.NET Web Control Feature rich, More consistent, Properties

Which of the following are programming languages which support


writing a Microsoft
Web application? (Choose all correct answers)
a. VB.NET
b. C#
c. C++.NET
d. Java
e. J#
f. ASP.NET
Which of the following languages/scripting languages are case
sensitive? (Choose all correct answers)
g. HTML
h. C#
i. JavaScript
j. VB.NET
k. Java
l. C++
Which of the following is/are true about the different types of Form
controls? (Choose all correct answers)
m.HTML controls are processed by client-side codes.
n. To have server-side codes control over HTML controls, we
can convert HTML control to HTML server control by
adding the attribute runat="server".
o. ASP.NET Web controls are processed by server-side codes
only.
p. ASP.NET Web controls are processed and interpreted into
HTML controls before they are sent to the browser.

Topic 2 : Web Forms & Server Controls (Part 2)


Event Handlers
Methods that are executed when the events happen
Allows you to write the codes to perform tasks in response to events
Client-Side Event Handlers
Used only with HTML controls only
Interpreted by the browser and run on the client
Cannot directly access server resources E.g.Database
Uses <script type=text/javascript>
Server-Side Event Handlers
Used with both Web(asp.net controls) and HTML server controls
Code is compiled and run on the server
Can directly access server resources E.g.Database
Use <script language=cs runat=server>
ASP.NET Event Handlers
ASP.NET event handlers are usually in the same ASPX page that the control
is on
When a control triggers an event, the ASPX page will make a HTTP Request
for itself
(Postback re-request)
The request includes information about the event
E.g.
<asp:TextBox ID=tb_name runat=server
ontextchanged=tb_name_TextChanged
AutoPostBack=True>
<asp:TextBox>
Postback occurs when an ASPX page is called second or more times due to
control events
(First request, NOT postback, Second Request(re-request), IS postback)
Use this.Page.IsPostBack to determine whether it is a PostBack
returns true when a control event activates the retrieval for the same page
returns false when you view the web page on a browser the very first time
e.g. When a button is clicked, a request is sent back to the web server to
request the page again(is

nowPostBack is set to true), so the text of the label is set toWhen the first
time the page is
loaded(isPostBack is set to false), the text pf the label is set to
*Change the method name Page_Load to Page_Start. What will display?
[]. Page_Load is the method to be executed before the page is loaded. It is
executed before the web form is loaded. Every time before the web form is
loaded, a few events are executed. These include Page_Load and the event
handlers for all the controls.
*Page.IsValid checks all validation controls are valid before performing tasks

Types of Validator Controls


RequiredFieldValidator must fill in data for the associated control
e.g. userid
CompareValidator compares value entered by the user in an input control
with the value
entered into another input control
e.g. passwords controltovalidate tb_pwdCfm
controltocompare tb_pwd
RangeValidator checks whether the value of an input control is within a
specified range of
values
e.g. age
RegularExpressionValidator - validates whether the value of an input
control matches with
a regular expression
e.g. e-mail address,postal code, phone
number,URL
Custom Validator customizable, performs user-defined validation on an
input control
e.g. checkboxes
ValidationSummary display summary of validation errors

Topic 3 : State Management


Problem without State
Difficult to track information across multiple pages
Cannot identify the user identity for e-commerce purposes
Cannot track hit counters
Cannot remember user settings and preferences

Server-Side State Management


1. Application State(ASP.NET)
information is available to all users of a Web application (Global scope)
E.g. Hit Counters, No. of visitors currently, provide information on how long
the application
has been started
2. Session State
Information is available only to a user of a specific session (Session scope)
E.g. Store the current users name and password, provide information
about the service
usages by the current user, store the preferences of the current user
like language
string username = tb_username.Text; Session[saveuname] =
username;
when loaded, it greets the user , in Page_Load
if(Session[saveuname] ! = null){
lb_name.Text = Session[saveuname].ToString();
}
3. Database
can use database support to maintain state on your website
Stores state information in database
Usually large amount of data, for long term permanent storage
When to Use??
Application State
Storing infrequently changed, global information that is used by many

users and security is not an issue.


Do not store large quantities of information in application state.
Session State
Short-lived information that is specified to an individual session and
security is
an issue
Do not store large quantities of information in session state
Database support
Storing large amounts of information
Security is an issue
Difference between Application & Session state
Data stored in the Application state has global scope. All users of the
application in all web pages are able to access the same data. For session
state, each browser session has a different value for the same declared
session object(variable).

Client Side State Management


1. Cookies
Cookies contain state information which is stored at the client side(browser
cache for
persistent cookies, or browser memory for temporary cookies). This
information is not stored
at servers at all
Can be retrieved between pages or any other sessions
Types of cookies : Persistent Cookies & Temporary/Non-persistent cookies
Persistent cookies -> Small text files stored in the client machine. They
have life spans which
are set by the web application. Upon expiry, they
will no longer be valid.
Temporary cookies -> Also known as session cookies. They exist in the
temporary memory of
the client browser. Once the browser is closed,
the cookie is removed.
e.g. //Add cookie
HttpCookie mycookie = new HttpCookie(visitCookie);
mycookie.Values.Add(username,tb_name.Text);
Response.Cookies.Add(mycookie);
//Retrieve cookie
HttpCookie thecookie;
thecookie = Request.Cookies[visitCookie];

UsrName = mycookie.Values[username];
Advantages/Disadvantages of using Cookies rather than server-side
management solutions
Advantages
Can store state information for long period of time(maybe even years)
without impacting
server performance
Simple technology which is widely supported by most Web browsers today
Disadvantages
Privacy & security issues Hackers can access the information if data is
not encrypted
Some browsers may not support cookies, or offer the user the option to
turn off cookies

2. The ViewState property(ASP.NET)


Retains values between multiple requests 4 e same page
The view state of each page is hidden and encrypted in the HTML page
3. Query Strings
Information appended to the end of a URL
Allows information to pass between the server and client from a page to
the next page(or
same page again)
When to use?
View State
store small amounts of information for a page that will post back to itself
Cookies
store small amounts of information on the client and security is not an
issue
retrieve between pages or across sessions
Query String
transferring small amount of information from one page to another and
security is not an
issue

Client-state management VS server-based state management

Server Resource
Security

Bandwidth

Browser Support

Storage Capacity

Client Based
No server resources
required
Information stored
on client has higher
risk of being
tempered or
modified
Information passes
back and forth
between client and
server
Certain techniques
may face problems
due to incompatible
browser or user
performance
(e.g. cookie)
Usually limited

Server-based
Server resources
required
More secure as
information is stored
on the server and
not transmitted to
the client
No information is
passes back and
forth between client
and server. Less
traffic
No need to worry as
information are not
passed to clients

Almost unlimited if
stored in a database

Topic 5 : Data Access (Part 1)


Sql Command
CREATE TABLE STRUCTURE Create Student Table
INSERT(Add rows) INSERT INTO StudentTable VALUES(Ong Yi Han ,
013813A , 155)
- INSERT INTO StudentTable VALUES (Wong Lo,
0310301J, ,159)
SELECT(Retrieve) SELECT * FROM StudentTable
SELECT Name, height FROM StudentTable WHERE
(height>=170)
ORDER BY Name
SELECT * FROM StudentTable WHERE Height=150
UPDATE(Change) UPDATE StudentTable SET Name=Ong Li WHERE
Name=Li Shah

- UPDATE StudentTable SET Height=155 WHERE


Admin=001Z
- UPDATE StudentTable SET Height=180
DELETE(Remove DELETE FROM StudentTable WHERE Name=Lee
Heng Kee
- DELETE FROM StudentTable WHERE Height<160

Topic 5 : Data Access (Part 2)


Clasess are found in the System.Data;
ADO.NET Architecture
DataProvider
Allows us to connect to the data source and to execute SQL
commands against it
Connection Object Establish a Connection to the
database(e.g.SqlConnection)
Command Object Execute commands/SQL Statements (e.g.
SqlCommand)
In retrieve/update results,
DataReader Object Reads a forward-only,read-only stream of data
from the
database, Results can also be loaded into a
DataTable
- Uses fewer server resources, fast access to
data
- Manage the connection yourself, manage the
data yourself
DataAdapter Object Fills a DataSet/DataTable with data(retrieve
-Fill() method) and
updates changes in the DataSet to the
database
( Update() method )
- Acts as a bridge between the DataSet object
and the data src
DataSet Holds the data in memory that we are working with while
we are
disconnected from the data source

3 Steps to access database from your program


Establish connection using connection object e.g. SqlConnection)
Construct SQL command(s) using command object (e.g. SqlCommand)
Get the return results using command object (e.g. SqlCommand)
Code used to establish connection
SqlConnection con = new
SqlConenctionStrings[StudentCS].ConnectionString;
OR
SqlConnection con = new SqlConnection();
con.ConnectionString
=ConfigurationManager.ConnectionStrings[StudentCS].ConnectionStr
ing;

Command object to setup the sql command issued to the


database/Link the command object to the connection object
SqlCommand cmd = new SqlCommand(sql,con);
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
dr = cmd.ExecuteReader();
Command Object ( represents an SQL statement)
1. ExecuteReader
to perform an Select
returns multiple-value result in DataReader object
2. ExecuteNonQuery
to perform an Insert/delete/update
does not return any result value
3. ExecuteScalar
performs to return the number of rows
returns a single value result
Reading Data

1.Create Connection Object


SqlConnection con = new SqlConnection();
con.ConnectionString =
ConfigurationManager.ConnectionStrings[studentCS].ConnectionStrin
g;
2.Construct SQL
string sql = Select AdminNo From studentTable
3.Create Command and DataReader
SqlCommand cmd = new SqlCommand(sql,con);
SqlDataReader dr = new SqlDataReader();
4.Open connection, ExecuteReader
con.Open();
dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr); //load to database
con.Close();

Topic 5 : ASP.NET Applications

1. Customized Default Error Page


Handles errors that are unhandled, not predicted, has no solution
Usually a .html page (instead of aspx page)
- Advantage: Will still work even if the ASP.NET engine of the web server is
not
functioning
-Disadvantage: Not able to use ASP.NET features like Master Pages
2. C# Exception Handling
When C# code encounters an error, it will throw an exception
We use the try.. catch statement to catch the exception and write code to
handle it
Throwing & Catching Exceptions standard way of handling errors in
current versions
many mainstream programming
languages
try
{
//Normal program errors
}
catch ([type of exception] ex1)
{
//error handling code
}
catch ([type of exception] ex2)
{
//error handling code
}
Example
try
{
age = Convert.Int32(tbAge.Text);
}
catch (FormatException fmtEx)
{
lblErrMsg.Text = Please enter a number.;
}
catch (Exception ex)

{
lblErrMsg.Text = Unknown error.;
}

1.

The two fundamental components of ADO.NET are _______________.


Connection and SQL Command
DBMS and relationships
DataProvider and DataSet
DataAdapter and DataTable

1 points

Question 2
1.

In ASP.NET, the connection string is stored in the _______________.


aspx
data.config
machine.config
Web.config

1 points

Question 3
1.

The ____________ method is used to perform a Select command.

ExecuteReader
ExecuteNonQuery
ExecuteScalar
ExecuteQuery

1 points

Question 4
1.

The ____________ method is used to return the number of rows.

ExecuteReader
ExecuteNonQuery
ExecuteScalar
ExecuteQuery

1 points

Question 5
1.

The ____________ method is used to perform an Insert/delete/update command.

ExecuteReader
ExecuteNonQuery
ExecuteScalar
ExecuteQuery

1 points
1.

Question 6

Which is NOT a valid file extension used for ASP.NET?


.aspx
.master
.config
.web

1 points

Question 7
1.

Which of the following is NOT an option of the server-side state management?


Application State
View State
Session State
Database Support

1 points

Question 8
1.

Which of the following is NOT an option of the client-side state management?


Database Support
View State
Cookies
Query String

1 points

Question 9
1.

A Web Form requires the user to enter an valid URL.


Which control should you use to validate the contents of the TextBox containing the URL?
RegularExpressionValidator
RangeValidator
RequiredFieldValidator
CustomValidator

1 points
1.

Question 10

Which of the following is NOT a method of the Command object?


ExecuteQuery

ExecuteScalar
ExecuteReader

ExecuteNonQuery

Вам также может понравиться