Basic Structural Concepts of .NET

advertisement
Basic Structural Concepts of
.NET
Managing State & Scope
Christopher M. Pascucci
What is State
 State refers to data maintained by an application for a single user.
 An application must maintain a separate state for each user.
 HTTP is a stateless protocol, which means it doesn’t maintain state
between roundtrips.
 Since HTTP is stateless the web applications must handle this.
Client
Browser
Browser
Browser
First HTTP request:
The browser requests a
page.
First HTTP response:
The server returns the
requested page and the
application ends.
Next HTTP request:
The browser requests another
page. The server has no way
to associate the browser with
its previous request.
Server
Web server
Web server
Web server
How ASP.NET Maintains State






ViewState (Page)
Session
Request
Application
Cookies
Cache
How ASP.NET Maintains State
 ViewState (Page)
 Maintains the values of form controls and properties that are NOT stored in the
HTTP header.
•
•
•
HTML form elements post their values to the HTTP header when the form is submitted.
ASP.NET uses the header to repopulate the form on a postback.
Even W3C got this one wrong and said that the ViewState stores this.
 ViewState is implemented by default.
 When a webform (aspx) is loaded, it can re-post to itself by means of a form
submit.
 A special state Boolean variable named IsPostBack is set to False when the
page is initially loaded, and to True after its first postback.
 Page state is maintained across postbacks to a single page by a single user.
 Page state is sometimes called ViewState, because there is a ViewState object
that contains property values for controls in the webform as well as the user
created attribute/value collection; however, only simple data types and
serializable objects can be stored in the ViewState object.
 ViewState is maintained across postbacks.
•
•
It stores the information (encrypted) in a hidden field in the form.
<input type="hidden" name="__VIEWSTATE"
value="dDwtMzQzNDc3MjYyO3Q8O2w8aTwyPjs+O2w8dDw7bDxpPDY+O2k8Nz47PjtsPHQ8cDxwP
Gw8VGV4dDs+O2w8SEVMTE8gTVIuIEEgQTs+Pjs+Ozs+O3Q8cDxwPGw8VGV4dDs” />
Using ViewState
 There are a few cases that you may want to disable ViewState
1. When it affects the way you want the form to work
2. When the size of the ViewState field gets so large that it affects performance.
 You can enable or disable view state for a form control by setting its EnableViewState
Property to True or False.
Example: txtName.EnableViewState = False
OR use the Property Window in Design Mode
 You can use ViewState for your own data

Adding or Updating a ViewState Item
ViewState.Add(“SubTotal”, dblSubTotal)
ViewState(“SubTotal”) = 155.79

Retrieving data from a ViewState Item
Dim myTotal As Double = Ctype(ViewState(“SubTotal”), Double)

Removing an item from ViewState
ViewState.Remove(“SubTotal”)
How ASP.NET Maintains State
 Session
 Session state is unique to each user of an application but maintained throughout
their use of the application.
 A Session is started when a user sends a URL to activate a given web site or
Application.
 The session can end in one of 3 ways:
1. If there is no request sent for a time called the Session Inactive Time.
There is a default value set within the web server for this time, but it can be
overridden by the session.Timeout property for a particular session object.
2. By the program using the session.Abandon method
3. If the client is terminated by closing the browser window, but Session
Inactive Time will still have to elapse.
Using Session State Object
 You can use the Session object to store your own data that can be used by other
pages or on PostBacks to maintain state.

Adding or Updating a Session Item
Session.Add(“Username”, strUsername)
Session(“Username”) = “cp2579”

Retrieving data from a ViewState Item
Dim strUsername As String = Ctype(Session(“Username”), String)

Removing an item from Session
Session.Remove(“Username”)
Property
Description
SessionID
The unique ID of the session.
Item(name)
The value of the session state item with the specified
name. If you set a value for an item that doesn’t
exist,that item is automatically created.
Count
The number of items in the session state collection.
TimeOut
Time in minutes until the session ends after no
requests are made by the user. Property is R/W.
Abandon
Destroys the session object and releases its
resources.
Method
Description
Add(name, value)
Adds an item to the session state collection.
Clear
Removes all items from the session state collection.
Remove(name)
Removes the item with the specified name from the
session collection.
How ASP.NET Maintains State
 Request
 A Request object is created whenever a URL request is made from the browser
to a web server.
 Request state is maintained during the life of a single request object. This means
from one page to the next only, like in a single redirect.
•
HTTP is stateless so information from a previous request is lost.
 The program can access data from web form controls on the server-side by
simply using Request(“FormControlName”) in the code.
 Application
 Application state is shared among all users (sessions) of an application.
 It can be used to maintain values that apply to all users and you can add your
own data/values to the application state object.
 The Application is all pages contained in a given web site. The application starts
when the first user sends a URL to the web server on which the web is located.
It ends when the last client (user) of the web ends its session or when the
application is stopped / restarted.
Using Application State Object
 You can use the Application object to store your own data that can be used by other
pages or on PostBacks to maintain state.

Used the same way as Session object to store, update, retrieve and remove items.
Example: Application(“UsersCount”) = count + 1

Since the Application state object is used by all users of the application across all
pages there are issues about updating items. You should use synchronization, Lock()
and Unlock() methods, so that items are updated properly.
Property
Description
Item(name)
The value of the application state item with the
specified name. If you set a value for an item that
doesn’t exist,that item is automatically created.
Count
The number of items in the application state
collection.
Method
Description
Add(name, value)
Adds an item to the application state collection.
Clear
Removes all items from the application state
collection.
Remove(name)
Removes the item with the specified name from the
application state collection.
Lock()
Locks the application state collection so only the
current user can access it.
Unlock()
Unlocks the application state collection so other users
can access it.
How ASP.NET Maintains State
 Cookies
 Cookie state is maintained in the client browser and can persist across page,
session and application state.
 It can even persist after the application terminates, for any predetermined time
period. Its lifetime can be programmatically controlled.
 Two types of cookies:
•
•
Session cookies – kept in the browser’s memory and exists until the session ends.
Persistent cookies – stored on the user’s hard drive and is retained until the cookie’s expiration date
or until the user deletes it.
 Cache
 Cache state has application scope but variable lifetime determined by the
following events:
• Specific files or database tables being updated
• Another Cache attribute changes value
• Time expiration
ASPX Browser – Server Interaction
Global.asax File
 This file contains a CodeBehind file that consists of application level events raised by
ASP.NET and that can be used to maintain state in your web application.

If you view the CodeBehind file the stubs for the events are automatically written for you. All you have to do
is place your code in the correct event.
 Any URL request for this file is rejected. External users cannot download or view the
code written within it.
 The global.asax file can be placed in the web at the directory level just below the
application root.
 Events: Runs the first time a user runs any page in your application
Sub Session_OnStart
...
End Sub
Runs when a user's session terminates
Sub Session_OnEnd
...
End Sub
Runs when the server loads an application for the first time
Sub Application_OnStart
...
End Sub
Runs when the application terminates
Sub Application_OnEnd
...
End Sub
The End…
 For more information on the CIS4309 website see the
maintaining state & scope pages.
 From more information about the Instrinsic HTTP objects
covered in this lecture.
 These slides discussed a good portion of the Intrinsic HTTP
objects (Request, Response, Session, Application, Server) , but
there is additional material on this topic not covered in these
slides.
Download