building web applications using asp.net, ajax and - UC Berkeley
Transcript of building web applications using asp.net, ajax and - UC Berkeley
AGENDA
6. ASP.NET Application and State Management
6.1 Anatomy of an ASP.NET Application
6.2 ASP.NET configuration
6.3 ASP.NET State Management
6.4 ASP.NET View State
6.5 Query String
6.6 Cookies
6.7 Session State
Building Web Applications Using ASP.NET, AJAX And JavaScript
6. ASP.NET APPLICATION AND STATE
MANAGEMENT
6.1 ANATOMY OF AN ASP.NET APPLICATION
End user does not run an ASP.NET application directly! User
requests page, the web server passes request to IIS.
IIS or ASP.NET worker process associates requested page with
application domain depending on virtual directory.
Application domain is boundary enforced by the CLR to ensure
that one application cannot influence (see in-memory data) of
another.
All web pages in a single web application share:
Same in-memory resources, such as global app data, per user session
data, and cached data.
Same configuration settings (web.config file!)
94
6.1 ANATOMY OF AN ASP.NET APPLICATION
All web applications raise global application events at various stages (application_start, application_end, application_error).
Use global.asax file in virtual directory to react to global application events.
Virtual directory is basic grouping structure the delimits an ASP.NET application. Application may consists of:
Web pages (aspx files)
Web services (asmx files)
Code files (cs files)
Configuration file (web.config file)
Global.asax file
Other components, such as compiled assemblies (ddl files)
Application Lifetime ASP.NET uses lazy initializing techniques (meaning app domain is created the first time a page is requested).
95
6.1 ANATOMY OF AN ASP.NET APPLICATION
Application shuts down when the server itself goes down. More
commonly, application restarts in a new app domain when an
error occurs, or when configuration or source files are changed.
Application Updates
Remarkable feature: You can update the web application without
restarting the web server. Old requests are still valid and
application operates using the old files, whereas the updated
application is created in a new domain.
ASP.NET uses shadow copy, a process that takes places during
compilation and copies all files into a temporary directory from
which the application is being run and files are locked.
ASP.NET tracks changes to its source files in order to trigger this
process.
96
6.1 ANATOMY OF AN ASP.NET APPLICATION
Application Directory Structure
97
Directory Description
Bin This directory contains all the precompiled .NET assemblies (usually DLLs) that the ASP.NET web application uses. These
assemblies can include precompiled web-page classes, as well as other assemblies referenced by these classes. (If you’re
using the project model to develop your web application in Visual Studio, rather than the more common website model, the
Bin directory will also contain an assembly that has the compiled code for your entire web application. This assembly is
named after your application, as in WebApplication1.dll.
App_Code This directory contains source code files that are dynamically compiled for use in your application. These code files are
usually separate components, such as a logging component or a data access library. The compiled code never appears in the
Bin directory, as ASP.NET places it in the temporary directories used for dynamic compilation. (If you are using the project
model to develop your web application in Visual Studio, rather than the more common website model, you do not need to
use the App_Code directory. Instead, all the code files in your project are automatically compiled into the assembly for your
web application alongside your web pages.)
App_GlobalResources This directory stores global resources that are accessible to every page in the web application.
App_LocalResources This directory serves the same purpose as App_GlobalResources, except these resources are accessible for their dedicated
page only.
App_WebReferences This directory stores references to web services that the web application uses. This includes WSDL files and discovery
documents.
App_Data This directory is reserved for data storage, including SQL Server Express or MS Access database files and XML files. Of
course, you are free to store data files in other directories.
App_Browsers This directory contains browser definitions stored in XML files. These XML files define the capabilities of client-side browsers
for different rendering actions. Although ASP.NET does this globally (across the entire computer), the App_Browsers folder
allows you to configure this behavior for separate web applications.
App_Themes This directory stores the themes used by the web application.
6.1 ANATOMY OF AN ASP.NET APPLICATION
Global.asax Application File
One global.asax file per application, must reside in root of virtual
folder.
Global.asax file is a code file only, no HTML or other tags.
This file cannot be requested by the end user.
The initial global.asax file only contains the most common
events, add other ones by simply typing the event framework
and the corresponding code.
Used to write event handlers that react to global events:
Events that occur for every page request
Events that occur under certain conditions (such as an error)
98
6.1 ANATOMY OF AN ASP.NET APPLICATION
Request and Response related events (page request)
99
Event Description
Application_BeginRequest() This method is called at the start of every request.
Application_AuthenticateRequest() This method is called just before authentication is performed. This is a jumping-off point for
creating your own authentication logic.
Application_AuthorizeRequest() After the user is authenticated (identified), it is time to determine the user’s permissions. You can
use this method to assign special privileges.
Application_ResolveRequestCache() This method is commonly used in conjunction with output caching. With output caching, the
rendered HTML of a web form is reused, without executing any of your code. However, this event
handler still runs.
At this point, the request is handed off to the appropriate handler. For example, for a web form request, this is the point when the page is
compiled (if necessary) and instantiated.
Application_AcquireRequestState() This method is called just before session-specific information is retrieved for the client and used to
populate the Session collection.
Application_PreRequestHandlerExecute() This method is called before the appropriate HTTP handler executes the request.
At this point, the appropriate handler executes the request. For example, if it is a web form request, the event-handling code for the page is
executed, and the page is rendered to HTML.
Application_PostRequestHandlerExecute() This method is called just after the request is handled.
Application_ReleaseRequestState() This method is called when the session-specific information is about to be serialized from the
Session collection so that it’s available for the next request.
Application_UpdateRequestCache() This method is called just before information is added to the output cache. For example, if you’ve
enabled output caching for a web page, ASP.NET will insert the rendered HTML for the page into
the cache at this point.
Application_EndRequest() This method is called at the end of the request, just before the objects are released and
reclaimed. It’s a suitable point for cleanup code.
6.1 ANATOMY OF AN ASP.NET APPLICATION
Execution based events (not based on page request)
101
Event Description
Application_Start() This method is invoked when the application first starts up and the
application domain is created. This event handler is a useful place to provide
application-wide initialization code. For example, at this point you might load
and cache data that will not change throughout the lifetime of an application,
such as navigation trees, static product catalogs, and so on.
Session_Start() This method is invoked each time a new session begins. This is often used to
initialize user-specific information. Chapter 6 discusses sessions with state
management.
Application_Error() This method is invoked whenever an unhandled exception occurs in the
application.
Session_End() This method is invoked whenever the user’s session ends. A session ends
when your code explicitly releases it or when it times out after there have
been no more requests received within a given timeout period (typically 20
minutes). This method is typically used to clean up any related data.
However, this method is only called if you are using in-process session state
storage (the InProc mode, not the StateServer or SQLServer modes).
Application_End() This method is invoked just before an application ends. The end of an
application can occur because IIS is being restarted or because the
application is transitioning to a new application domain in response to
updated files or the process recycling settings.
Application_Disposed() This method is invoked some time after the application has been shut down
and the .NET garbage collector is about to reclaim the memory it occupies.
This point is too late to perform critical cleanup, but you can use it as a last-
ditch failsafe to verify that critical resources are released.
6.2 ASP.NET CONFIGURATION
Configuration in ASP.NET is managed with XML configuration
files.
Advantages over traditional ASP classic configuration:
They are never locked: You can update configuration files while the
application is running (switching domains).
Easily accessed and updated: Maintain, copy, and paste configuration
files like any other files.
Easily understood and easy to maintain: Settings in configuration files are
human-readable! No special tool needed.
You cannot do the following:
Create or remove virtual directories
Change file mappings, for example to process requests for
additional file types, such as HTML.
Use IIS Manager on the server.
103
6.2 ASP.NET CONFIGURATION
Machine.config file
Configuration starts with machine.config file that resides in
directory:
c:\Windows\Microsoft.NET\Framework\v2.0.50727\Config
The machine.config file defines supported configuration file
sections, configures the ASP.NET worker process, and registers
providers that can be used for advanced features such as
profiles, membership, and role-based security.
Along with the machine.config file, ASP.NET uses a root
web.config file (in the same directory) that contains additional
settings.
All the web applications on the computer inherit the settings in
these two files. However, most of the settings are essentially
plumbing features that you never need to touch.
104
6.2 ASP.NET CONFIGURATION
Web.config file
Set up custom settings for individual web applications:
Specific method for authentication
Type of debugging
Default language
Custom error pages
Use web.config file in root directory of web application.
To further configure subfolders, place additional web.config files in these subfolders.
Application-specific settings cannot be overriden by web.config files in subfolders.
All settings are nested in root <configuration> element
105
6.2 ASP.NET CONFIGURATION
Inheritance concept
of machine and
web.config file
<system.web>
sections contains
all ASP.NET specific
settings.
Schema is fixed,
cannot change or
add custom sections
106
Config
C:\Windows\Microsoft.NET\Framework\v2.0.50727\
machine.config web.config
Virtual Directory
web.config
Sub Directory
web.config
C:\Temp\WebApps\Library
6.2 ASP.NET CONFIGURATION
107
Child elements of
<System.Web>
Element Description
authentication This element determines how you will verify a client’s identity when the client requests a
page. This is set at the application level (in other words, in the web.config file that is in
the web application’s root virtual directory).
authorization This element controls which clients have access to the resources within the web
application or current directory.
compilation Contains the <assemblies> element, which lists the assemblies your web application
uses. These assemblies are then made available to your code (as long as they can be
found in the Bin directory or the GAC).
customErrors Allows you to set specific redirect URLs that should be used when specific (or default)
errors occur. For example, this element could be used to redirect the user to a friendly
replacement for the dreaded 404 (page not found) error.
identity Controls the security identity of the ASP.NET application. You can use this setting to cause
the web application to temporarily assume the identity of another Windows account and
its permissions and restrictions. This setting is set at the application level.
httpHandlers Defines the classes that process the HTTP requests your application receives. For
example, requests for files with the extension .aspx are automatically handled by the
System.Web.UI.PageHandlerFactory class, which runs the page life cycle. If you are using
the ASP.NET integration features in IIS 7, this section is superseded by the <handlers>
section in the <system.webServer> element.
httpModules Defines classes that are given a chance to react to every request your web application
receives. For example, ASP.NET’s session state and authentication features work through
dedicated modules.
pages Defines default page settings (most of which you can override with the Page directive).
ASP.NET 3.5 applications also use the <pages> element to provide access to the new
controls from the System.Web.Extensions.dll assembly.
sessionState Configures the various options for maintaining session state for the application, such as
whether to maintain it at all and where to maintain it (SQL, a separate Windows service,
and so on). This is set at the application level.
trace Configures tracing, an ASP.NET feature that lets you display diagnostic information in the
page (or collect it for viewing separately).
6.3 ASP.NET STATE MANAGEMENT
Fact is, HTTP is a stateless protocol!
After every web page request, the client disconnects from the server.
ASP.NET discards any object created for this web page.
This architecture ensures that web applications can scale up to serve thousands of simultaneous requests without running out of server memory.
The drawback is that your code needs to use other techniques to store information between web requests and retrieve it when needed.
ASP.NET includes a variety of options for state management.
Select the right option depending on the data you need to store, the length of time you want to store it, the scope of your data (whether it is limited to individual users or shared across multiple requests), and additional security and performance considerations.
110
6.3 ASP.NET STATE MANAGEMENT
Category View State Query String Custom Cookies
Allowed data types All serializable .NET data
types.
A limited amount of string
data.
String data only.
Storage location A hidden field in the
current web page.
The browser’s URL String. The client’s computer (in
memory or a small text
file, depending on its
lifetime settings).
Lifetime Retained permanently for
postbacks to a single
page.
Lost when the user enters a
new URL or closes the browser.
However, can be stored and
can persist between visits.
Set by the programmer.
It can be used in multiple
pages and it persists
between visits.
Scope Limited to the current
page.
Limited to the target page. The whole ASP.NET
application.
Security Tamper-proof by default
but easy to read. You can
use the Page directive to
enforce encryption.
Clearly visible and easy for the
user to modify.
Insecure and can be
modified by the user.
Performance Storing a large amount of
information will slow
transmission but will not
affect server performance.
None, because the amount of
data is small by design.
None, because the
amount of data is small
by design.
Typical use Page-specific settings. Sending a product ID from a
catalog page to a details page.
Personalization
preferences for a website.
111
6.3 ASP.NET STATE MANAGEMENT Category Session State Application State Profiles Caching
Allowed data
types
All serializable .NET data types.
Nonserializable types are supported
if you are using the default in-
process state service.
All .NET data types. All serializable .NET data
types.
All .NET data types. Nonserializable
types are supported if you create a
custom profile.
Storage
location
Server memory (by default), or a
dedicated database, depending on
the mode you choose.
Server memory. A back-end database. Server memory.
Lifetime Times out after a predefined period
(usually 20 minutes but can be
altered globally or
programmatically).
The lifetime of the
application (typically, until
the server is rebooted).
Permanent. Depends on the expiration policy
you set, but may possibly be
released early if server memory
becomes scarce.
Scope The whole ASP.NET application. The whole ASP.NET
application. Unlike most
other types of methods,
application data is global to
all users.
The whole ASP.NET
application. May also be
accessed by other
applications.
The same as application state
(global to all users and all pages).
Security Secure, because data is never
transmitted to the client. However,
subject to session hijacking if you do
not use SSL.
Very secure, because data is
never transmitted to the
client.
Fairly secure, because
although data is never
transmitted, it is stored in a
database that could be
compromised.
Very secure, because data is never
transmitted to the client.
Performance Storing a large amount of
information can slow down the
server severely, especially if there
are a large number of users at once,
because each user will have a
separate set of session data.
Storing a large amount of
information can slow down
the server, because this data
will never time out and be
removed.
Large amounts of data can
be stored easily, but there
may be a nontrivial
overhead in retrieving and
writing the data for each
request.
Storing a large amount of
information may force out other,
more useful cached information.
However, ASP.NET has the ability to
remove items early to ensure
optimum performance.
Typical use Store items in a shopping basket. Storing any type of global
data.
Store customer account
information.
Storing data retrieved from a
database.
112
6.4 VIEW STATE
View state should be your first choice for storing information
within the bounds of a single page.
View state is used natively by the ASP.NET web controls. It allows
them to retain their properties between postbacks.
You can add your own data to the view state collection using a
built-in page property called ViewState.
View state relies on a dictionary collection, where each item is
indexed with a unique string name.
ViewState[“FirstName”] = “Bob”;
This puts the string value Bob into the ViewState collection.
If FirstName already exists, it is overwritten, otherwise it is
added.
113
6.4 VIEW STATE
When retrieving a value, you use the key name.
You also need to cast the retrieved value to the appropriate data type.
ViewState collection casts all items to the base Object type, which allows it to handle any type of data.
View state is ideal because it does not take up any memory on the server and does not impose any arbitrary usage limits (such as a time-out).
Drawbacks:
If you need to store mission-critical information (security).
Storing information across pages.
Storing large amount of information.
ViewState adds to size of page, thereby increasing transmission time.
114
6.5 QUERY STRING
ViewState works great when posting to the same page.
What if we need to post to a different page? One solution is to use Query String.
Commonly used for search engines, navigation, etc. For example, Google search: http://www.google.com/search?q=asp.net+session
This defines a variable q with a value of asp.net+session.
Query string is lightweight and does not burden the server. Drawbacks are:
Limited to simple strings, which must contain URL-legal characters.
Information is clearly visible to the user and to anyone else who cares to eavesdrop on the Internet.
The curios user might decide to modify the query string and supply new values, which your program will not expect and cannot protect against.
Many browsers impose a limit on the length of a URL (usually from 1 to 2 KB).
117
6.5 QUERY STRING
One potential problem with the query string is using characters
that are not allowed in a URL.
Characters must be alphanumeric or one of a small set of
special characters (including $-_.+!*’(),).
Furthermore, some characters have special meaning. (&, ?, +)
119
6.6 COOKIES
Cookies are small files that are created on the client’s hard drive
(or, if they are temporary, in the web browser’s memory).
They also can be easily used by any page in your application and
even retained between visits, which allows for truly long-term
storage.
Drawbacks:
Limited to simple string information
Easily accessible and readable if the user finds and opens the
corresponding file.
These factors make them a poor choice for complex or private
information or large amounts of data.
Both the Request and Response objects
provide a Cookies collection.
120
6.7 SESSION STATE
Probably best tool of session management!
It allows information to be stored in one page and accessed in
another, and it supports any type of object, including your own
custom data types.
Session state uses the same collection syntax as view state.
Every client that accesses the application has a different
session and a distinct collection of information.
Session state is ideal for storing information such as the items in
the current user’s shopping basket when the user browses from
one page to another.
Session information is stored on the server! Server generates
unique SessionID that is passed with every page request using a
cookie.
122
6.7 SESSION STATE
To store a value: Session[“LoggedInUser”] = value
To retrieve a value: variable = Session[“LoggedInUser”]
Session state is global to your entire application for the current user. Session state can be lost in several ways:
If the user closes and restarts the browser.
If the user accesses the same page through a different browser window.
If the session times out because of inactivity. By default, a session times out after 20 idle minutes.
If the programmer ends the session by calling Session.Abandon().
123
Member Description
Count The number of items in the current session collection.
IsCookieless Identifies whether this session is tracked with a cookie or with modified URLs.
IsNewSession Identifies whether this session was just created for the current request. If there
is currently no information in session state, ASP.NET won’t bother to track the
session or create a session cookie. Instead, the session will be re-created with
every request.
Mode Provides an enumerated value that explains how ASP.NET stores session state
information. This storage mode is determined based on the web.config
configuration settings.
SessionID Provides a string with the unique session identifier for the current client.
StaticObjects Provides a collection of read-only session items that were declared by <object
runat="server"> tags in the global.asax file. Generally, this technique isn’t used
and is a holdover from ASP programming that is included for backward
compatibility.
Timeout The current number of minutes that must elapse before the current session will
be abandoned, provided that no more requests are received from the client. This
value can be changed programmatically, giving you the chance to make the
session collection longer term when required for more important operations.
Abandon() Cancels the current session immediately and releases all the memory it
occupied. This is a useful technique in a logoff page to ensure that server
memory is reclaimed as quickly as possible.
Clear() Removes all the session items but doesn’t change the current session identifier.