You are on page 1of 288

ASP.

NET
Session Prerequisites
 This session assumes that you
understand the fundamentals of
 Development on Windows®
 ASP or Visual Basic®
Agenda
 Introduction to .NET
 ASP Today
 ASP.NET
 Server Controls
 Data Controls
 ASP.NET Web Applications
 Business Objects
 Web Services
Introduction to .NET
ASP.NET

VB C++ C# JScript …

Common Language Specification

Visual Studio.NET
ASP.NET: Web Services Windows
and Web Forms Forms

ADO.NET: Data and XML

Base Class Library

Common Language Runtime


Agenda
 Introduction to .NET
 ASP Today
 ASP.NET
 Server Controls
 Data Controls
 ASP.NET Web Applications
 Business Objects
 Web Services
ASP Today
Successes
 Simple procedural programming model
 Access to COM Objects
 ADO
 File system object
 No compiling, just save
 Support for Multiple Scripting languages
 Mix HTML and Code
 VBScript – Leverage VB Skills
ASP – ASP.NET Differences
 Code Readability – No spaghetti code
 Language Interoperability
 Compiled –
 The .NET Framework detects that the page is being run for
the first time and compiles it, storing the copy of it.
 In the traditional approach to ASP, pages were interpreted on
each request to the page
 Strongly typed –
 In traditional ASP, programmers were provided with only
variant data type, consuming more memory and not providing
ways for early binding -- something that is now possible with
ASP.NET.
 Web forms –
 Web Forms provide a rich UI of the pages in ASP.NET
 Web Services
ASP – ASP.NET Differences
 Control-based event-driven programming
model –
 Makes it easy to create powerful applications
similar to VB applications
 GUI and event logic separated
 Separate code and presentation –
 ASP.NET provides a powerful technique called
code behind. which allows you to separate code
from presentation.
 PostBack Complexity
 Code Reuse
 Deployment - No registry –
 This allows deployment by simply copying the
files, without having to bother with registry issues
ASP – ASP.NET Differences
 DLL Locking –
 In the previous versions of ASP, when the script used the
functions, the DLL was locked in the memory.
 Although ASP.NET cannot prevent the CLR from locking a
loaded assembly DLL on disk, it can support you by
ensuring that the physical DLLs in a Web application's
private assembly cache are never actually loaded by the
runtime.
 Instead, shadow copies of the assembly DLLs are made
immediately prior to their use.
 These shadow assemblies--not the original files--are then
locked and loaded by the runtime.
 Because the original assembly files always remain unlocked,
you are free to delete, replace, or rename them without
cycling the Web server or having to use a registration utility.
 With ASP.NET, the Framework detects the new version and
replaces the old one
 Sessions
ASP – ASP.NET Differences
 Caching –
 Pages, and even parts of pages that are frequently
requested can now be cached for better
performance.
 Validation controls and server controls –
 For common validation a programmer used to
write a lot of code.
 This was difficult if there were different client
types for your page.
 A set of server controls, along with validation
controls, render the HTML, which is specific to the
client.
 The programmer can even build several powerful
controls based on their specific needs
Agenda
 Introduction to .NET
 ASP Today
 ASP.NET
 Server Controls
 Data Controls
 ASP.NET Web Applications
 Business Objects
 Web Services
ASP.NET Design Goals
 Event-based programming model similar
to Microsoft Visual Basic®

 Compiled code and support for multiple


languages, as opposed to ASP which was
interpreted

 Allows third parties to create controls


that provide additional functionality –
custom (user) controls
ASP.NET Design Goals
 Rich set of validation controls that
reduce client-side programming

 Viewstate management using hidden


controls
ASP.NET
Architecture

ASPX

.ASPX
ASP.NET
Architecture

Partially,
the auto-generated class,
along with a compiled instance of
Compiled .ASPX
the class, is stored in the:
WINDOWS\Microsoft.NET\Framework\version\Temporary ASP.NET Files folder,
ASP.NET
Architecture

All the subsequent page requests directly execute


the compiled code.

The runtime creates one instance of this


class per AppDomain.
Compiled .ASPX
One distinct AppDomain per running
ASP.NET Application is maintained.
ASP.NET
Architecture

Compiled .ASPX
Code behind
System.Web.UI.Page
class

inherits

MyWebForm.aspx.vb
class

inherits

MyWebForm.aspx
DLL creation – ASP.NET 1.1
 The code behind files for all the web forms in the project are compiled
into a DLL before deployment

 All .aspx file compiled into another DLL at runtime

 The ASP.NET runtime dynamically compiles an ASP.NET page the first


time a user requests it.

 First, it checks its cache to see whether that page has been compiled
already.

 If it hasn't, it loads the .aspx file and generates a temporary source


code file that implements a class that represents that ASP.NET page.

 It then invokes the appropriate command-line compiler to compile the


generated source code into an assembly.

 Finally, the class that represents the ASP.NET page is instantiated to


handle the incoming request.
DLL creation – ASP.NET 2.0
 Second, you no longer have to separately compile your user-defined
code into an assembly that gets copied into the application's \bin
directory.

 All code, both generated and user-defined is now compiled by the


ASP.NET runtime into a single class.

 There is a new compileWith attribute in the @Page declaration. This


tells the ASP.NET runtime the name of the code separation file that
contains user-defined code.

 ASP.NET 1.x inherits attribute is no longer present. Recall that this


attribute told the ASP.NET 1.x runtime what class to derive the
ASP.NET page from.

 The code for button click in the code behind file is linked with the
button in the aspx file with the onclick attribute.
The default.aspx file in ASP.NET 1.x.
 <%@ Page debug="true" language="c#" Codebehind="Default.aspx.cs"
Inherits="Test._Default" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >


<HTML> <HEAD> <title>Default</title> </HEAD>
<body> <form id="Form1" method="post" runat="server">
<P>
<asp:Label id="Label1" runat="server">Hello, World!
</asp:Label>
</P>
<P>
<asp:Button id="Button1" runat="server" Text="Click Me">
</asp:Button>
</P>
</form> </body>
</HTML>
The code-behind file: default.aspx.cs in ASP.NET 1.x.

 namespace Test {
public class _Default : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Button Button1;
private void Page_Load(object sender, System.EventArgs e)
{ // Put user code to initialize the page here }

#region Web Form Designer generated code


override protected void OnInit(EventArgs e)
{ // // CODEGEN: This call is required by the ASP.NET Web Form //
Designer. // InitializeComponent(); base.OnInit(e);
}

private void InitializeComponent()


{ this.Button1.Click += new
System.EventHandler(this.Button1_Click); this.Load += new
System.EventHandler(this.Page_Load); }
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{ Label1.Text = "Clicked me!"; }
} }
The default.aspx file in ASP.NET 2.0.

 <%@ page debug="true" language="C#"


compilewith="Default.aspx.cs" %>

<html> <head runat="server"> <title>Untitled


Page</title> </head>
<body> <form runat="server">
<asp:label id="Label1" runat="server">Hello, World!
</asp:label> <br /> <br />
<asp:button id="Button1" runat="server" text="Click
Me“ onclick="Button1_Click" />
</form> </body>
</html>
The code separation file: default.aspx.cs in
ASP.NET 2.0.
 using System;
namespace ASP
{
public partial class Default_aspx
{
void Button1_Click(object sender,System.EventArgs e)
{
Label1.Text = "Clicked me!";
}
}
}
ASP.NET 2.0 – Page Compilation Model

 The new code for the code separation file,


default.aspx.cs. only contains the event handler for
Button1's Click event.

 The reason this code is so much simpler is due to a


language feature called partial classes that is new to
both C# and VB.NET.

 This feature lets a class definition span multiple


source files, which is how VS.NET and ASP.NET can
hide all of the standard initialization code from you.

 To understand how partial classes work, we need to


take a closer look at the code that is generated by the
ASP.NET runtime.
ASP.NET 2.0 – Page Compilation Model

 There isn't a build step; you immediately start


running your Web application.

 The ASP.NET code no longer runs in IIS during


development. Instead, it runs in a new managed Web
server called Visual Web Developer Web Server.

 This new design means that you don't need to install


or configure IIS on a developer's computer.

 It also means that you can develop ASP.NET code


using a restricted user account without having to
reconfigure ASP.NET first.
ASP.NET 2.0 – Page Compilation Model
 After we run the application for the first time, we need to find
where ASP.NET places the generated files.

 It turns out, they're in a different location now. Because the


Visual Web Developer Web Server runs using your credentials,
you'll find the files in Local Settings\Temp\Temporary ASP.NET
Files\[virtual root]\[x]\[y].

 The code that the ASP.NET runtime generated for the


default.aspx page, declares part of the code for a class called
Default_aspx; its class definition is declared using the C# partial
keyword.

 This code is combined at compile-time with the code which


contains the rest of the definition of the Default_aspx class.
Both of these files were compiled using the C# compiler into a
new assembly.
ASP.NET – Page Compilation Model
 The new page compilation model in ASP.NET 2.0 is simpler
because all the code for an ASP.NET page now resides in a single
class; there isn't a forced division of labor between the base class
and the derived class.

 Reduces developer error; in ASP.NET 1.x, you could forget to


recompile or copy your code-behind assemblies to the \bin
directory of your Web application. You could also accidentally
"change" the code in your code-behind file that has event handlers.

 ASP.NET now takes care of compiling all of the code in your Web
application, so that you have far fewer opportunities to make a
mistake while building or deploying your application.

 You can pre-compile your entire application into a single set of


assemblies. This is done using a new command-line utility called
aspnet_compiler.

 This makes it possible to deploy an ASP.NET application without


copying any source code files to a production server.
ASP.NET
Execution Model
Source VB C# C++
code
Unmanaged
Compiler Compiler Compiler
Component

Managed Assembly Assembly Assembly


code IL Code IL Code IL Code

Common Language Runtime

JIT Compiler

Native Code

Operating System Services


ASP.NET
Features
 ASPX, ASP – Side by Side
 Simplified Programming Model
 Simplified Deployment
 Better Performance
 Caching
 Powerful Controls
ASP.NET
Features
 Simplified Browser Support
 Simplified Form Validation
 Code Behind Pages
 More Powerful Data Access
 Web Services
 Better Session Management
ASP.NET
Features
 No DLL Locking
 No DLL Registration
 Simplified Configuration
 Off-Line Capabilities
 Pagelets
Browser Compatibility – Browser Levels

 2 categories of browsers –
 Up level
 Support Jscript and JavaScript Version 1.2
 HTML version 4.0
 Microsoft Document Object Model (MSDOM)
 Cascading Style Sheets (CSS)
 Only the latest versions of IE fall under this
category
 Down level
 HTML version 3.2
Browser Compatibility
 ASP.NET server side controls automatically
determine the browser level that has
requested the page, and generate HTML code
appropriate to that browser.

 Thus, the need to code separately for different


browsers and their versions is eliminated.

 Just drop the sever side control on the form,


at runtime the server generates the
appropriate code.
Browser Compatibility
 For up level browsers, the server
controls will generate client-side
JavaScript that manipulates the MSDOM
and traps the action events directly on
the client-side.

 For down level browsers, the server


controls generate the standard HTML,
that requires the browser to perform a
round-trip to the server for triggered
action events
Anatomy of an ASP.NET Project
Anatomy of an ASP.NET Project
 Global.asax –
 Similar to the Global.asa file. Contains global events for this
Web Application

 Global.vb –
 This contains the event handling code corresponding to the
Global.asax

 HelloWorld.aspx (by default, this file is called


WebForm1.aspx) -
 This is where your ASP\HTML controls go in.

 HelloWorld.vb –
 This contains the event handling code for the corresponding
.aspx file

 Styles.css –
 Style sheet that can be used across the application
ASP.NET
 In classic ASP all Web site related information was stored in the
metadata of IIS.
 Disadvantage that remote Web developers couldn't easily make Web-site
configuration changes.
 for example, if you want to add a custom 404 error page, a setting needs to
be made through the IIS admin tool, and you're Web host will likely charge
you a fee to do this .

 With ASP.NET, these settings are moved into an XML-formatted


text file (Web.config) that resides in the Web site's root
directory.

 Through Web.config you can specify settings like custom 404


error pages, authentication and authorization settings for the
Web site, compilation options for the ASP.NET Web pages, if
tracing should be enabled, etc
ASP.NET config files
 Each configuration file contains a nested hierarchy of XML tags
and subtags with attributes that specify the configuration
settings.

 Tags, subtags, and attributes are case-sensitive.

 Tag names and attribute names are camel-cased, which means


that the first character of a tag name is lowercase and the first
letter of any subsequent concatenated words is uppercase.

 Attribute values are Pascal-case, which means that the first


character is uppercase and the first letter of any subsequent
concatenated words is uppercase.

 Exceptions are true and false, which are always lowercase.


ASP.NET config files
 2 files related to configuration
 Web.config
 Machine.config

 Web.config is by default created for every web


application and is present in the application folder

 Web.config is used to specify application level


configurations

 Machine.config is used to specify machine level


configurations and is present under:
 C:\ WINNT\ Microsoft.NET\ Framework\ v1.1.4322\ CONFIG
ASP.NET config files
 Machine.config has <appSettings> tag that applies
configurations to applications.

 This tag should be used by developers to apply


common settings for all the applications

 For specific application settings web.config should


be used, this keeps machine.config manageable

 Deploying an application using XCOPY does not copy


the machine.config hence application settings given
in this file are left out
ASP.NET config files
 Multiple configuration files, all named
Web.config, can appear in multiple directories
on an ASP.NET Web application server.

 Each Web.config file applies configuration


settings to its own directory and all child
directories below it.

 Configuration files in child directories can


supply configuration information in addition
to that inherited from parent directories, and
the child directory configuration settings can
override or modify settings defined in parent
directories.
ASP.NET config files
 At run time, ASP.NET uses the configuration information provided by
the Web.config files

 The configuration settings are then cached for all subsequent requests

 ASP.NET detects changes to configuration files and automatically


applies new configuration settings to Web resources affected by the
changes.

 The server does not have to be rebooted for the changes to take effect.

 ASP.NET help protect configuration files from outside access by


configuring Internet Information Services (IIS) to prevent direct browser
access to configuration files.

 HTTP access error 403 (forbidden) is returned to any browser


attempting to request a configuration file directly.
ASP.NET config files
 Specifying Application-Wide Settings in
Web.config
 At the root level is the <configuration> tag.

 Inside this tag you can add a number of other


tags, the most common and useful one being the
<system.web> tag, where you will specify most of
the Web site configuration parameters.

 To specify application-wide settings you use the


<appSettings> tag.

 Inside this tag you can specify zero or more


settings by using the <add ... /> tag.
ASP.NET config files
 For example,
 <configuration> <!-- application specific settings -->
<appSettings>
<add key="connString" value="connection string" />
</appSettings>
<system.web> ... </system.web>
</configuration>

 Now, in any of the ASP.NET Web pages in the Web site you can
read the value of the connString parameter like:
 Dim myConnection as New
SqlConnection(ConfigurationSettings.AppSettings("connString")
ASP.NET config files
 Specifying Classes of Application-Wide Settings
 While you can use the appSettings tag if you intend to sell this
Web application or have it be used on other people's Web
sites, placing such parameters in the appSettings tag may
lead to problems.

 For example, imagine that you have a connection string


parameter named connString that you want to let be
configurable, so you create a key in the appSettings tag
named connString, as we did above. Well, imagine that the
person who's installing your application is trying to integrate
with his already-existing Web site. She might already have
such a configuration settings, which means she'll have to
change her setting and all the pages that reference it, to some
name that doesn't conflict with any of your setting names.

 Ideally you'd like not to present your end user with this
headache. To avoid this complication you can "group" your
application's settings into a unique tag in the Web.config file.
That is, you can create a tag named: <MyAppSettings> in
Web.config and then use the <CODE<ADD code >< ...>as we
did earlier to add application-wide settings.
ASP.NET config files <customErrors/> tag

 Helps in custom error handling


 Giving user friendly error messages
 Errors can be handled on
 Page level OR
 Application level
Page Level Error Handling
 Handle the Page_Error event of the
ASP.NET page as follows:
protected override void Page_Error(EventArgs e)
{ // At this point we have information about the error

HttpContext ctx = HttpContext.Current;  


Exception exception = ctx.Server.GetLastError ();
string errorInfo = "<br>Offending URL: " +
ctx.Request.Url.ToString () + "<br>Source: " +
exception.Source + "<br>Message: " +
exception.Message + "<br>Stack trace: " +
exception.StackTrace; 
ctx.Response.Write (errorInfo); 
// To let the page finish running we clear the error
ctx.Server.ClearError ();
Page Level Error Handling
 This will work for only one page
 So this code has to be repeated on each
page
 Instead you can follow the Page
Controller Pattern
Application Level Error Handling
 Remember the Global.asax file!

 From the moment you request a page in your browser to the moment
you see a response on your screen a complex process takes place on
the server.

 Your request travels through the ASP.NET pipeline.

 In the eyes of IIS each virtual directory is an application.

 When a request within a certain virtual directory is placed, the pipeline


creates an instance of HttpApplication to process the request.

 The runtime maintains a pool of HttpApplication objects. The same


instance of HttpApplication will service a request it is responsible for.

 This instance can be pooled and reused only after it is done processing
a request.
Application Level Error Handling
 The ASP.NET runtime parses your global.asax,
compiles a class derived from HttpApplication and
hands it a request for your web application.

 HttpApplication fires a number of events.

 One of them is Error.

 To implement your own handler for application-level


errors your global.asax file needs to have code

 When any exception is thrown now—be it a general


exception or a 404—it will end up in
Application_Error.
Application Level Error Handling
 protected void Application_Error(Object
sender, EventArgs e)
{ // At this point we have information about
the error
HttpContext ctx = HttpContext.Current; 
Exception exception =
ctx.Server.GetLastError (); 
string errorInfo = "<br>Offending URL: "
+ ctx.Request.Url.ToString () +
"<br>Source: " + exception.Source +
"<br>Message: " + exception.Message +
"<br>Stack trace: " + exception.StackTrace; 

ctx.Response.Write (errorInfo); 
// To let the page finish running we clear the
error ctx.Server.ClearError ();
Application Level Error Handling
 Be careful when modifying global.asax.

 The ASP.NET framework detects that


you changed it, flushes all session state
and closed all browser sessions and—
in essence—reboots your application.

 When a new page request arrives, the


framework will parse global.asax and
compile a new object derived from
HttpApplication again.
Setting Custom Error Pages In
web.config
 If an exception has not been handled by the
Page object, or the HttpApplication object and
has not been cleared through
Server.ClearError() it will be dealt with
according to the settings of web.config.

 When you first create an ASP.NET web


project in Visual Studio .NET you get a
web.config for free with a small
<customErrors> section:

 <customErrors mode="RemoteOnly" /> With


this setting your visitors will see a canned
error page.
Setting Custom Error Pages In
web.config
 The mode attribute can be one of
the following:
 On – error details are not shown to anybody, even
local users. If you specified a custom error page it
will be always used.

 Off – everyone will see error details, both local


and remote users. If you specified a custom error
page it will NOT be used.

 RemoteOnly – local users will see detailed error


pages with a stack trace and compilation details,
while remote users with be presented with a
concise page notifying them that an error
occurred. If a custom error page is available, it will
be shown to the remote users only.
Setting Custom Error Pages In
web.config
 Displaying a concise yet not-so-pretty
error page to visitors is still not good
enough, so you need to put together a
custom error page and specify it this
way:
 <customErrors mode="RemoteOnly"
defaultRedirect="~/errors/GeneralError.as
px" />

 Now, when the error occurs you will see a


detailed stack trace and remote users will be
automatically redirected to the custom error
page, GeneralError.aspx.
Setting Custom Error Pages In
web.config
 The <customErrors> tag may also contain
several <error> subtags for more granular
error handling.

 Each <error> tag allows you to set a custom


condition based upon an HTTP status code.
 E.g. you may display a custom 404 for missing
pages and a general error page for all other
exceptions:
 <customErrors mode="On“
defaultRedirect="~/errors/GeneralError.aspx">
<error statusCode="404"
redirect="~/errors/PageNotFound.aspx" />
</customErrors>

 The URL to a custom error page may be relative


(~/error/PageNotFound.aspx) or absolute.

 The tilde (~) in front of URLs means that these URLs


ASP.NET Session State
 Session is the time duration during which the client is
connected to the server.

 Every session has a start time, end time and session


ID

 A session expires when the user logs out or when the


session time out period elapses, with no activity from
the client

 In traditional ASP sessions were managed by the web


server process using cookies and the session ID
ASP.NET Session State
 Session ID is an alphanumeric value created by the
server to uniquely identify the client.

 This value is sent by the server to the client and is


stored on the client machine is a text file called
cookie.

 With every client request this cookie data is sent to


the web server so that the server recognizes the
client and handles the session data for that client

 This method of session handling in ASP was called


in-process since session handling was done by the
same process which manages the web server and
was cookie based.
ASP.NET Session State
 This method had some drawbacks-
 Process dependent –
 ASP session state exists in the process that hosts ASP; thus
the actions that affect the process also affect session state.
When the process is recycled or fails, session state is lost.
 Session data cannot persist across server starts
 Server farm limitations –
 Session data cannot be shared by multiple servers where there
are web server farms.
 In-process session handling is machine specific and the
session data remains on the machine in which the session
handling process is running
 So if the client visits another server in the server farm the
session data is not accessible there
 Cookie dependent -
 Clients that don't accept HTTP cookies can't take advantage of
session state.
 Some clients believe that cookies compromise security and/or
privacy and thus disable them, which disables session state on
the server.
ASP.NET Session State
 ASP.NET session state solves all of the above problems
associated with classic ASP session state:
 Process independent –
 ASP.NET session state is able to run in a separate process from the
ASP.NET host process.
 If session state is in a separate process, the ASP.NET process can
come and go while the session state process remains available. Of
course, you can still use session state in process similar to classic
ASP, too.
 Support for server farm configurations –
 By moving to an out-of-process model, ASP.NET also solves the server
farm problem.
 The new out-of-process model allows all servers in the farm to share a
session state process.
 You can implement this by changing the ASP.NET configuration to point
to a common server.
 Cookie independent –
 ASP.NET implements cookieless session state by using simple
configuration setting in the web.config file, <sessionstate> tag.
ASP.NET Session State
 Session state settings in ASP.NET are
configured through the ASP.NET XML
configuration file config.web.

 <configuration>
<sessionstate mode="inproc"
cookieless="false" timeout="20"
sqlconnectionstring="data
source=127.0.0.1;user id=<user
id>;password=<password>"
server="127.0.0.1" port="42424" />
</configuration>
ASP.NET Session State
 Attributes of the sessionstate tag -
 Mode –
 The mode setting supports three options: inproc, sqlserver, and
stateserver.
 As stated earlier, ASP.NET supports two modes: in process and
out of process.
 There are also two options for out-of-process state
management: memory based (stateserver), and SQL Server
based (sqlserver).
 Cookieless –
 The cookieless option for ASP.NET is configured with this simple
Boolean setting.
 Timeout –
 This option controls the length of time a session is considered valid.
 The session timeout is a sliding value; on each request the timeout
period is set to the current time plus the timeout value
ASP.NET Session State
 Sqlconnectionstring - The sqlconnectionstring identifies the
database connection string that names the database used for
mode sqlserver.

Server - In the out-of-process mode stateserver, it names the
server that is running the required Windows NT service:
aspnet_state.

Port - The port setting, which accompanies the server setting,
identifies the port number that corresponds to the server setting
for mode stateserver.
ASP.NET Session State
 In-process Mode –
 In-process mode simply means using ASP.NET session state in a similar
manner to classic ASP session state.

 That is, session state is managed in process and if the process is re-cycled,
state is lost.

 Given the new settings that ASP.NET provides, you might wonder why you
would ever use this mode.

 The reasoning is quite simple: performance. The performance of session


state, e.g. the time it takes to read from and write to the session state
dictionary, will be much faster when the memory read to and from is in
process, as cross-process calls add overhead when data is marshaled back
and forth or possibly read from SQL Server.

 In-process mode is the default setting for ASP.NET. When this setting is
used, the only other session web.config settings used are cookieless and
timeout.

 So after setting a session state value, stop and start the ASP.NET process
(iisreset), the value set before the process was cycled will be lost.
ASP.NET Session State
 Out-of-process Mode
 Included with the .NET SDK is a Windows® NT service: ASPState.
This Windows service is what ASP.NET uses for out-of-process
session state management. To use this state manager, you first
need to start the service. To start the service, open a command
prompt and type:
 net start aspnet_state
ASP.NET
In web.config
Session State
 <configuration>
<sessionstate mode="stateserver"
cookieless="false" timeout="20"
sqlconnectionstring="data source=127.0.0.1;user id=<user
id>;password=<password>" server="127.0.0.1"
port="42424" />
</configuration>

 We changed only from inproc mode to stateserver mode.

 This setting tells ASP.NET to look for the ASP state service on
the server specified in the server and port settings—in this case,
the local server.

 Now set a session state value, stop and start the IIS process
(iisreset), and continue to have access to the values for our
current state.
ASP.NET Session State
 SQL Server Mode
 The SQL Server mode option is similar to that of the
Windows NT Service, except that the information persists to
SQL Server rather than being stored in memory.
 To use SQL Server as our session state store, we first must
create the necessary tables and stored procedures that
ASP.NET will look for on the identified SQL Server. The .NET
SDK provides us with a SQL script (state.sql) to do just that.
 state.sql
 The state.sql file contains the SQL commands used to create
the ASPState database. This script creates two tables and
several stored procedures. ASP.NET uses both the tables
and the procedures to store data in SQL Server. I would
recommend reading through state.sql to learn more about
what it is doing.
 The state.sql file can be found in [system
drive]\winnt\Microsoft.NET\Framework\[version]\
ASP.NET Session State
 In web.config
 <configuration>
<sessionstate mode="sqlserver" cookieless="false"
timeout="20" sqlconnectionstring="data
source=MySqlServer; user id=ASPState;
password=1Gr8State" server="127.0.0.1"
port="42424" />
</configuration>
 Now set a session state value, stop and start the IIS process
(iisreset), and continue to have access to the values for our
current state.
 In fact, we could cluster the SQL Servers such that if one SQL
Server happened to be unavailable, another server that was
replicating its data could take its place.
 This provides a level of reliability that was not available in ASP.
ASP.NET Session State
 Cookieless State –
 This feature allows sites whose clients
choose not to use cookies to take
advantage of ASP.NET session state.
 This is done by modifying the URL with an
ID that uniquely identifies the session:
 http://localhost/(lit3py55t21z5v55vlm25s55)/App
lication/SessionState.aspx
 ASP.NET will modify relative links found within
the page and embed this ID.
 Thus, as long as the user follows the path of
links the site provides, session state can be
maintained.
 However, if the end user re-writes the URL, the
session state instance will most likely be lost.
ASP.NET Session State
 In web.config -
 <configuration>
<sessionstate mode="stateserver"
cookieless="true" timeout="20"
sqlconnectionstring="data
source=127.0.0.1;user id=<user
id>;password=<password>"
server="127.0.0.1" port="42424" />
</configuration>
 Once cookieless is set to true, ASP.NET will
do the work necessary to enable cookieless
session state. Also note that all modes are
supported for cookieless sessions.
Authorization & Authentication
 Authentication and Authorization are two interrelated security
concepts.

 Authentication is a process of identifying a user, while


authorization is the process of determining if an authenticated
user has access to the resource (s) they requested.

 Authentication is achieved by the user sharing credentials that


verify the user's identity.

 Whenever a user logs on to an application, the user is first


authenticated and then authorized.

 ASP.NET Web applications, by default, allow the users


requesting a page, an anonymous access.

 There are different techniques available for determining the


identity of an anonymous user.
Authentication & Authorization
 Understanding how ASP.NET and IIS Handle
Authentication and Authorization
 Both IIS - Microsoft's Web server software - and ASP.NET
provide means for authentication and authorization.

 ASP.NET is not a stand-alone product - rather, it utilizes IIS.

 When a request comes in for an ASP.NET Web page, the


request is sent to the Web server software (IIS), which
performs authentication and authorization.

 Depending on the settings in IIS and the user accessing the


site, these checks might pass or they might not.

 If the user is not authenticated, or does not have access,


they're request will be stopped and an appropriate message
will be returned.

 If, however, the request passes IIS's authentication and


authorization, the request will be handed off to the ASP.NET
engine, which can impose its own authentication and
authorization schemes.
Authentication & Authorization
 The following shows the sequence of authentication
and authorization actions performed by IIS and
ASP.NET on an incoming request.
 The incoming request is first checked by IIS. If the IP
address from where the request is sought is not allowed
access to the domain, IIS denies the request.

 IIS allows anonymous access by default and hence requests


are automatically authenticated. However, this can be
overridden for each application within IIS. Next in the
sequence IIS performs this authentication, if it has been
configured to do so.

 The authenticated user request is passed to ASP.NET.

 ASP.NET checks whether Impersonation is enabled or not.


By default impersonation is not enabled in ASP .NET.
Authentication & Authorization
 If impersonation is enabled, ASP.NET executes with the
identity of the entity on behalf of which it is performing
executing the task.

 If impersonation is not enabled, the application runs with the


privileges of the ASPNET user account.

 Finally, the identity that has been authenticated and checked


for in the previous steps is used to request resources from
the OS.

 ASP.NET uses two forms of authorization:


 FileAuthorization - relies on NTFS file permissions for granting
access.
 UrlAuthorization - in the Web.config file you can specify the
authorization rules for various directories or files using the
<authorization> element.

 If access is granted (successful authorization), ASP .NET


returns the user's request through IIS.
Authentication & Authorization
Authentication & Authorization
 Authentication Providers –
 ASP.NET provides three ways to authenticate a
user:
 Windows authentication,
 Forms authentication, and
 Passport authentication

 It is the job of the authentication provider to verify


the credentials of the user and decide whether a
particular request should be considered
authenticated or not.

 The authentication scheme an ASP.NET Web


application uses can be configured in its
Web.config file.
Authentication & Authorization
 Windows Authentication Provider –
 The Windows authentication provider is the default provider for
ASP .NET.

 It authenticates users based on the users' Windows accounts.

 Windows authentication in ASP.NET actually relies on IIS to do the


authentication.

 IIS can be configured so that only users on a Windows domain can


log in.

 If a user attempts to access a page and is not authenticated, they'll


be shown a dialog box asking them to enter their username and
password.

 This information is then passed to the Web server and checked


against the list of users in the domain.

 If the user has supplied valid credentials, access is granted.

 The identity of the user is then passed to the ASP.NET engine.


Authentication & Authorization
 There are four different kinds of
Windows authentication options
available that can be configured in
IIS:
 Anonymous Authentication:
 IIS doesn't perform any authentication check.
IIS allows any user to access the ASP .NET
application.
 The server uses a built in account (IUSR_[
machine name] by default) to control the
permissions on the files.
 The browser does not send any credentials or
user info with this type of request.
 Browsers Supported: Any
 Encryption Type: None
Authentication & Authorization
 Basic Authentication (Clear Text) :
 For this kind of authentication, a Windows user name
and password have to be provided to connect.

 The server requests the user to log on and a dialog box


appears in the browser that allows the user to enter the
credentials that are needed.

 These credentials must match the user credentials


defined on the files that the user is attempting to access.

 However, this information is sent over the network in


plain text and hence this is an insecure kind of
authentication.

 Basic Authentication is the only mode of authentication


older, non-Internet Explorer browsers support.
Authentication & Authorization
 Digest Authentication:
 It is same as Basic Authentication but for the fact that the
password is hashed before it is sent across the network.
However, to be using Digest Authentication, we must use IE 5.0
or above.

 The server requests the user to log on and also sends a NONCE
used to encrypt the password.

 The browser uses the NONCE to encrypt the password and


sends this to the server.

 The server then encrypts its own copy of the user's password
and compares the two. If they match and the user has
permissions, access is granted.

 Browsers Supported: Internet Explorer 5 only

 Limitations: Not as secure as Integrated. Requires the server to


have access to an Active Directory Server that is set up for
Digest Authentication.

 Encryption Type: Based on NONCE sent by server.


Authentication & Authorization
 Integrated Windows Authentication (split
into two sub categories) :
 In this kind of authentication technique,
passwords are not sent across the network.

 The application here uses either the Kerberos


or challenge/response protocols to authenticate
users.
Authentication & Authorization
 Kerberos, a network authentication
protocol, is designed to provide strong
authentication for client-server
applications.

 It provides the tools of authentication and


strong cryptography over the network to
help to secure information in systems
across entire enterprise.
Authentication & Authorization
 The server requests a user to log on. If the
browser supports Kerberos, The following takes
place:
 IIS requests authentication.
 If the client has not logged on to a domain, a dialog box
appears in Internet Explorer requesting credentials, and
then contacts the KDC to request and receive a Ticket
Granting Ticket.
 It then sends the Ticket Granting Ticket along with
information about the IIS server to the KDC.
 If the IE Client has already successfully logged into the
domain and received a Ticket Granting Ticket, it sends
this ticket along with info about the IIS server to the KDC
 The KDC issues the client a Resource Ticket.
 The Client passes this ticket to the IIS server.
 Kerberos uses tickets generated at a Ticket Granting
Server (KDC) to authenticate. It sends this ticket to the IIS
server. The browser does NOT send the user's password
across to the server.
Authentication & Authorization
 Browsers Supported: Internet Explorer
versions 5.0 and above

 Limitations: the server must have access


to an Active Directory server. Both the
server and the client must have a trusted
connection to a KDC.

 Encryption type: Encrypted ticket.


Authentication & Authorization
 Windows NT Challenge/Response –
 The server requests the user to log on. If the browser
supports Windows NT Challenge/Response, it automatically
sends the user's credentials if the user is logged on.

 If the domain that the user is on is different than the server's


domain, or if the user is not logged on, a dialog box appears
in Internet Explorer requesting the credentials to send.

 Windows NT Challenge/Response uses an algorithm to


generate a hash based on the user's credentials and the
computer that the user is using. It then sends this hash to
the server. The browser does not send the user's password
across to the server.

 Browsers Supported: Internet Explorer versions 3.01 and


later.
Authentication & Authorization
 Limitations: Requires point-to-point connection. Typically, a
circuit is closed after a "401 unauthorized " error message;
however, when negotiating an Windows NT
Challenge/Response authentication sequence (which
requires multiple round trips), the server keeps the circuit
open for the duration of the sequence after the client has
indicated that it will use Windows NT Challenge/Response.

 CERN proxies and certain other Internet devices prevent this


from working. Also, Windows NT Challenge/Response does
not support double-hop impersonations (meaning that once
passed to the IIS server, the same credentials cannot be
passed to a back-end server for authentication, for example,
when IIS uses Windows NT Challenge/Response, it cannot
then authenticate the user against a SQL Server database on
another computer by using SQL Integrated security).

 User Rights Required: The user account accessing the


server must have "Access this computer from the network "
permissions.

 Encryption Type: NTLM Hash algorithm that is also


uuencoded.
Authentication & Authorization
 Orders of Precedence:
 When the browser makes a request, it always
considers the first request to be Anonymous.
Therefore, it does not send any credentials.

 If the server does not accept Anonymous or if the


Anonymous user account set on the server does
not have permissions to the file being requested,
the IIS server responds with an "Access Denied"
error message and sends a list of the
authentication types that are supported by using
one of the following scenarios:
 If Windows Integrated is the only supported method (or if
Anonymous fails), then the browser must support this
method to communicate with the server.

 The server tries Kerberos first, and if this fails, then the
server falls back to Windows NT Challenge/Response. If
this fails, the server does not try any of the other
methods.
Authentication & Authorization
 If Basic is the only supported method (or if Anonymous
fails), then a dialog box appears in the to get the credentials,
and then passes these to the server.

 It attempts to send the credentials up to three times. If these


all fail, the browser does not connect to the server.

 If both Basic and Windows Integrated are supported, the


browser determines which method is used. If the browser
supports Kerberos or Windows NT Challenge/Response, it
uses this method.

 It does not fall back to Basic. If Windows NT


Challenge/Response and Kerberos are not supported, the
browser uses Basic, Digest, or Fortezza if it supports these.

 The order of precedence here is Basic, Digest, and then


Fortezza.
Authentication & Authorization
 NOTES:
 When your browser establishes a connection with
a Web site by using Basic or Windows Integrated
authentication, it does not fall back to Anonymous
during the rest of that session with the server.

 If you try to connect to a Web page that is marked


for Anonymous only after authenticating, you are
denied. (This may or may not hold true for
Netscape).

 When Internet Explorer has established a


connection with the server by using an
authentication method other than Anonymous, it
automatically passes the credentials for every new
request during the duration of the session
Authentication & Authorization
 Passport Authentication Provider –
 Passport authentication is a centralized
authentication service.

 This uses Microsoft's Passport Service to


authenticate the users of an application.

 If the authentication mode of the application is


configured as Passport and if the users have
signed up with Microsoft's Passport Service, then
the authentication formalities are pushed over to
Passport servers.

 Passport uses an encrypted cookie mechanism to


identify and indicate authenticated users.
Authentication & Authorization
 If the users have already been signed into
passport when they visit the application
page, ASP.NET will consider them as
authenticated. Otherwise, the users will be
redirected to Passport servers to login.

 Upon successful login, the user is


redirected back to the ASP.NET Web page
that they initially tried to access.

 If you use Hotmail you already have a


Passport account and are familiar with the
sign-in process from an end-user's
perspective.
Authentication & Authorization
 Forms Authentication Provider –
 The forms authentication provider uses
custom HTML forms to collect
authentication information.

 As an ASP.NET developer using forms


authentication, you must write your own
logic/code to check the user's supplied
credentials against a database or some
other data store.

 When a user is successfully identified via


forms authentication, the user's credentials
are stored in a cookie for use during the
session.
Authentication & Authorization
 The method of authentication to use is specified in
the Web application's Web.config file:
 <!-- For Windows Authentication... -->
<authentication mode="windows">
<!-- For Passport Authentication... -->
<authentication mode="passport">
<!-- For Forms Authentication... -->
<authentication mode="forms">

 ASP .NET also supports custom authentication providers.

 Setting the authentication mode for the application to


"none" and then writing our own code to perform
authentication can achieve this.

 For example, we might install an ISAPI filter in IIS that


compares incoming requests' IP address with a list of
source IP addresses and considers the request to be
authenticated only if the IP address is found in the source
list. In this example, we can set the authentication mode to
"none" in Web.config file. This will prevent any of the default
authentication providers from being triggered.
ASP.NET Authorization
 The purpose of authorization is to
determine whether an identity should be
granted the requested type of access to
a given resource. There are two
fundamental ways to authorize access
to a given resource:
 File authorization
 Performed by the FileAuthorizationModule, and
is active when you use Windows
authentication.
 It does an access control list (ACL) check of the
.aspx or .asmx handler file to determine if a
user should have access.
 Applications can further use impersonation to
get resource checks on resources that they are
accessing.
ASP.NET Authorization
 URL authorization
 Performed by the URLAuthorizationModule, which maps
users and roles to pieces of the URL namespace.

 This module implements both positive and negative


authorization assertions.

 That is, the module can be used to selectively allow or


deny access to arbitrary parts of the URL namespace for
certain sets, users, or roles.

 The URLAuthorizationModule is available for use at any


time. You only need to place a list of users and/or roles in
the <allow> or <deny> elements of the <authorization>
section of a configuration file.
ASP.NET Authorization
 To establish the conditions for access to a
particular directory, you must place a
configuration file that contains an
<authorization> section in that directory.

 The conditions set for that directory also apply


to its subdirectories, unless configuration files
in a subdirectory override them.

 The general syntax for this section is as


follows:
 <[element] [users] [roles] [verbs]/> An element is
required. Either the users or the roles attribute must
be included. Both can be included, but both are not
required. The verbs attribute is optional
ASP.NET Authorization
 The permissible elements are <allow> and
<deny>, which grant and revoke access,
respectively.

 Each element supports three attributes, which


are defined in the following table.
 Attribute – Role –
 Identifies a targeted role for this element.
 The associated IPrincipal object for the request
determines the role membership.
 You can attach arbitrary IPrincipal objects to the context
for a given request and they can determine role
membership in whatever way you like.
 For example, the default WindowsPrincipal class uses
Microsoft Windows NT groups to determine role
membership.
ASP.NET Authorization
 Attribute – users
 Identifies the targeted identities for this element.

 Attribute – verbs
 Defines the HTTP verbs to which the action applies, such as GET, HEAD, and
POST.

 Anonymous users are also denied.

 The following example grants access to Kim and members of the


Admins role, while denying it to John and all anonymous users:
 <authorization>
<allow users="Kim"/>
<allow roles="Admins"/>
<deny users="John"/>
<deny users="?"/>
</authorization>
Both users and roles can refer to multiple entities by using a comma-
separated list, as shown in the following example.

 <allow users="John, Kim, contoso\Jane"/> Notice that the domain


account (contoso\Jane) must include both the domain and user name
combination.
ASP.NET Authorization
 In addition to identity names, there are two special identities, as
follows:
 * - Refers to all identities
 ? - Refers to the anonymous identity

 To allow John and deny everyone else, one might construct the
following configuration section.
 <authorization>
<allow users="John"/>
<deny users="*"/>
</authorization>

 The following example lets everyone do a GET, but only Kim can
use POST.
 <authorization>
<allow verb="GET" users="*"/>
<allow verb="POST" users="Kim"/>
<deny verb="POST" users="*"/>
</authorization>
ASP.NET Authorization
 Rules are applied using the following heuristics:
 Rules contained in configuration files at lower directory levels take precedence over
rules at higher directory levels.

 The system determines which rule takes precedence by constructing a merged list of
all rules for a URL, with the most recent (nearest in the hierarchy) rules at the head of
the list.

 Given a set of merged rules for a URL, the system starts at the head of the list and
checks rules until the first match is found.

 Note that the default configuration for ASP.NET contains an <allow users="*">
element, which authorizes all users.

 If no rules match, the request is allowed unless otherwise denied.

 If a match is found and the match is a <deny> element, it returns the 401 status code.

 Applications or sites can easily configure a <deny users="*"> element at the top level
of their site or application to prevent this behavior.

 If an <allow> matches, the module does nothing and lets the request be processed
further.

 There is also a <location> tag that you can use to specify a particular file or directory
to which settings wrapped by that tag (between <location> and </location> tags)
should apply.
ASP.NET Impersonation
 When using impersonation, ASP.NET applications can
optionally execute with the identity of the client on whose behalf
they are operating.

 The usual reason for doing this is to avoid dealing with


authentication and authorization issues in the ASP.NET
application code.

 Instead, you rely on Microsoft Internet Information Services (IIS)


to authenticate the user and either pass an authenticated token
to the ASP.NET application or, if unable to authenticate the user,
pass an unauthenticated token.

 In either case, the ASP.NET application impersonates whichever


token is received if impersonation is enabled.

 The ASP.NET application, now impersonating the client, then


relies on the settings in the NTFS directories and files to allow it
to gain access, or not.

 Be sure to format the server file space as NTFS, so that access


permissions can be set.
ASP.NET Impersonation
 Impersonation is disabled by default.

 For ASP compatibility, the user must explicitly enable


impersonation.

 If impersonation is enabled for a given application,


ASP.NET always impersonates the access token that
IIS provides.

 That token can be either an authenticated user token,


or the token for the anonymous user (such as
IUSR_MACHINENAME). The impersonation occurs
regardless of the type of authentication being used in
the application.

 Only application code is impersonated; compilation


and configuration are read as the process token.
ASP.NET Impersonation
 The result of the compilation is put in the "Temporary
ASP.NET files" directory.

 The account that is being impersonated needs to


have read/write access to this directory.

 If an application is on a universal naming convention


(UNC) share, ASP.NET will always impersonate the
token provided to IIS to access that share unless a
configured account is used.

 If an explicit configured account is provided,


ASP.NET will use that account in preference to the IIS
UNC token.

 Applications that do want per-request impersonation


can simply be configured to impersonate the user
making the request
ASP.NET Impersonation
 Impersonation is disabled at the computer level by default and,
unless overridden, all the application domains inherit this
setting.

 You can enable impersonation by putting a configuration file in


the application root directory.

 As is the case with other configuration directives, this directive


applies hierarchically.

 It is respected by nested applications in the hierarchy, unless


explicitly overridden.

 The default value for this setting is as follows.


 <impersonation enable="false"/>
 A minimal configuration file to enable impersonation for an
application might look similar to the following example.
 <!-- Web.config file. -->
<identity impersonate="true"/>
ASP.NET Impersonation
 There is also name support for running an application as a configurable
identity. For example:
 <identity impersonate="true" userName="contoso\Jane"
password="pass"/>
 This enables the entire application to run as contoso\Jane, regardless of the
identity of the request, as long as the password is correct. This type of
impersonation can be delegated to another computer.

 You can programmatically read the identity of the impersonated user,


as shown in the following example.
 [Visual Basic]Dim username As String =
System.Security.Principal.WindowsIdentity.GetCurrent().Name
 [C#]String username =
System.Security.Principal.WindowsIdentity.GetCurrent().Name;
 In the preceding example, userName and password are stored in clear text
in the configuration file.
 Although IIS will not transmit .config files in response to a user agent
request, configuration files can be read by other means, for instance by an
authenticated user with proper credentials on the domain that contains the
server.
 To help increase security, the identity section supports storage of encrypted
userName and password attributes in the registry as shown in the following
example.
 userName="registry:HKLM\Software\AspNetIdentity,Name"
password="registry:HKLM\Software\AspNetIdentity,Password"
ASP.NET Impersonation
 The portion of the string after the keyword
registry and before the comma indicates the
name of the registry key that ASP.NET opens.

 The portion after the comma contains a single


string value name from which ASP.NET will
read the credentials.

 The comma is required, and the credentials


must be stored in the HKLM hive.

 If the configuration format is incorrect,


ASP.NET will not launch the worker process
and the current account creation failure code
path will be followed.
ASP.NET Impersonation
 The credentials must be in REG_BINARY format,
containing the output of a call to the Windows API
function CryptProtectData.

 You can create the encrypted credentials and store


them in the registry with the ASP.NET Set Registry
console application(Aspnet_setreg.exe), which uses
CryptProtectData to accomplish the encryption.

 You should configure access to the key storing the


encrypted credentials so that access is provided only
to Administrators and SYSTEM.

 Because the key will be read by the ASP.NET process


running as SYSTEM, you should set the following
permissions:
 Administrators:F
 SYSTEM:F
 CREATOR OWNER:F
 ProcessAccount:R
ASP.NET Impersonation
 This provides two lines of defense to
protect the data:
 The ACL permissions require the identity
accessing the data to be an Administrator.
 An attacker must run code on the server
(CryptUnprotectData) to recover the
credentials for the account.
Implementing Impersonation
 Impersonate the IIS Authenticated
Account or User
 To impersonate the Microsoft Internet
Information Services (IIS) authenticating
user on every request for every page in an
ASP.NET application, you must include an
<identity> tag in the Web.config file of this
application and set the impersonate
attribute to true. For example:
 <identity impersonate="true" />
Implementing Impersonation
 Impersonate a Specific User for All the Requests of
an ASP.NET Application
 You can specify the userName and password attributes in
the <identity> tag of the Web.config file for that application.
For example:
 <identity impersonate="true" userName="accountname"
password="password" />
 Note: The identity of the process that impersonates a
specific user on a thread must have the "Act as part of the
operating system" privilege.
 By default, the Aspnet_wp.exe process runs under a
computer account named ASPNET.
 However, this account does not have the required privileges
to impersonate a specific user.
 You receive an error message if you try to impersonate a
specific user.
 This information applies only to the .NET Framework 1.0.
This privilege is not required for the .NET Framework 1.1.
Implementing Impersonation
 To work around this problem, use one
of the following methods:
 Grant the "Act as part of the operating
system" privilege to the ASPNET account
(the least privileged account).

 Note Although you can use this method to


work around the problem, Microsoft does
not recommend this method.

 Change the account that the


Aspnet_wp.exe process runs under to the
System account in the <processModel>
configuration section of the Machine.config
file.
Implementing Impersonation
 Impersonate the Authenticating User in Code
 (User.Identity) only when you run a particular section of
code, you can use the code to follow.

 This method requires that the authenticating user identity is


of type WindowsIdentity.

 Visual Basic .NET


Dim impersonationContext As
System.Security.Principal.WindowsImpersonationContext
Dim currentWindowsIdentity As
System.Security.Principal.WindowsIdentitycurrentWindows
Identity = CType(User.Identity,
System.Security.Principal.WindowsIdentity)impersonation
Context = currentWindowsIdentity.Impersonate()
'Insert your code that runs under the security context of the
authenticating user here.
impersonationContext.Undo()
ASP.NET Page Life Cycle
ASP.NET Page Life Cycle
 Each time a request arrives at a Web server
for an ASP.NET Web page, the first thing the
Web server does is hand off the request to
the ASP.NET engine.

 The ASP.NET engine then takes the request


through a pipeline composed of numerous
stages, which includes verifying file access
rights for the ASP.NET Web page,
resurrecting the user's session state, and so
on.

 At the end of the pipeline, a class


corresponding to the requested ASP.NET
Web page is instantiated and the
ProcessRequest() method is invoked
ASP.NET Page Life Cycle
 This life cycle of the ASP.NET page starts with a call
to the ProcessRequest() method.

 This method begins by initializing the page's control


hierarchy.

 Next, the page and its server controls proceed


through various steps which include managing view
state, handling postback events, and rendering the
page's HTML markup.

 The life cycle ends by handing off the Web page's


HTML markup to the Web server, which sends it back
to the client that requested the page.
ASP.NET Page Life Cycle
 Stage 0 - Instantiation
 The life cycle of the ASP.NET page begins with
instantiation of the class that represents the
requested ASP.NET Web page
 When an ASP.NET Web page is visited for the first
time the ASP.NET engine auto-generates a class
 The purpose of this auto-generated class is to
programmatically create the page's control
hierarchy.
 That is, the class is responsible for
programmatically creating the Web controls
specified in the page's HTML portion.
ASP.NET Page Life Cycle
 All ASP.NET server controls can have a
parent control, along with a variable
number of child controls.
 The System.Web.UI.Page class is derived
from the base control class
(System.Web.UI.Control), and therefore
also can have a set of child controls.
 The top-level controls declared in an
ASP.NET Web page's HTML portion are the
direct children of the auto-generated Page
class.
 Web controls can also be nested inside
one another.
ASP.NET Page Life Cycle
 Since server controls can have children, and each
of their children may have children, and so on, a
control and its descendents form a tree of
controls.
 This tree of controls is called the control
hierarchy.
 The root of the control hierarchy for an ASP.NET
Web page is the Page-derived class that is auto-
generated by the ASP.NET engine.
 When the control hierarchy is constructed, the
properties that are explicitly set in the declarative
syntax of the Web control are assigned in the
code.
 E.g. the Button Web control has its Text property
set to "Submit!" in the declarative syntax –
Text="Submit!" – as well as in the auto-generated
class—Button1.Text = "Submit!"
ASP.NET Page Life Cycle
ASP.NET Page Life Cycle
 Stage 1 - Initialization
 This stage is marked by having the Page
and controls fire their Init events.
 With regards to view state it is important
for two reasons;
 First, server controls don't begin tracking view
state changes until initialization stage is over.
 Second, when adding dynamic controls that
utilize view state, these controls will be added
during the Page's Init event and not during the
Load event
ASP.NET Page Life Cycle
 Stage 2 - Load View State
 The load view state stage only happens when the
page has been posted back.
 During this stage, the view state data that had
been saved from the previous page visit is loaded
and recursively populated into the control
hierarchy of the Page.
 It is during this stage that the view state is
validated.
 The view state can become invalid due to a
number of reasons, such as view state tampering,
and injecting dynamic controls into the middle of
the control hierarchy.
 LoadViewState method is commonly Overridden
to customize the data received by the control at
the time it is populated.
ASP.NET Page Life Cycle
 Stage 3 - Load Postback Data
 The load Postback data stage also only happens
when the page has been posted back.
 A server control can indicate that it is interested in
examining the posted back data by implementing
the IPostBackDataHandler interface.
 In this stage in the page life cycle, the Page class
enumerates the posted back form fields, and
searches for the corresponding server control. If it
finds the control, it checks to see if the control
implements the IPostBackDataHandler interface.
 If it does, it hands off the appropriate postback
data to the server control by calling the control's
LoadPostData() method.
 The server control would then update its state
based on this postback data.
ASP.NET Page Life Cycle
 Stage 4 - Load
 When the Load event fires, the view state
has been loaded, along with the postback
data. If the page has been posted back,
when the Load event fires we know that the
page has been restored to its state from
the previous page visit.
ASP.NET Page Life Cycle
 Stage 5 - Raise Postback Event
 This occurs after all controls that implement the
IPostBackDataHandler interface have been
updated with the correct postback data.
 During this operation, each control is flagged with
a Boolean on whether its data was actually
changed or remains the same since the previous
submit.
 ASP.NET then sweeps through the page looking
for flags indicating that any object's data has been
updated and fires RaisePostDataChanged.
 The RaisePostDataChanged event does not fire
until all controls are updated and after the Load
event has occurred.
 This ensures data in another control is not
manually altered during the
RaisePostDataChanged event before it is updated
with postback data.
ASP.NET Page Life Cycle
 Stage 6 - Save View State
 The Page class constructs the page's view
state, which represents the state that must
persist across Postback.
 The page accomplishes this by recursively
calling the SaveViewState() method of the
controls in its control hierarchy.
 This combined, saved state is then
serialized into a base-64 encoded string
and
 is persisted to the hidden __VIEWSTATE
form field.
ASP.NET Page Life Cycle
 Stage 7 - Render
 In the render stage the HTML that is
emitted to the client requesting the page is
generated.
 The Page class accomplishes this by
recursively invoking the RenderControl()
method of each of the controls in its
hierarchy.
ASP.NET Page Life Cycle
 Stage 8 – Disposal
 After the page's HTML is rendered, the
objects are disposed of.
 During the Dispose event, you should
destroy any objects or references you have
created in building the page.
 At this point, all processing has occurred
and it is safe to dispose of any remaining
objects, including the Page object.
The Role of View State
 View state's purpose in life is simple:
it's there to persist state across
postbacks.
 What sort of state needs to be
persisted? AND
 What state doesn't need to be persisted
across postbacks?
The Role of View State
 What state doesn't need to be persisted
across postbacks?
 In the instantiation stage of the page life
cycle, the control hierarchy is created and
those properties that are specified in the
declarative syntax are assigned.
 Since these declarative properties are
automatically reassigned on each postback
when the control hierarchy is constructed,
there's no need to store these property
values in the view state.
The Role of View State
 What sort of state needs to be persisted?
 Any programmatic changes to the page's state.
 For example,
 Suppose that in addition to a Label Web control, the page
also contained two Button Web controls, a Change
Message Button and an Empty Postback button.
 The Change Message Button has a Click event handler
that assigns the Label's Text property to "Goodbye,
Everyone!";
 The Empty Postback Button just causes a postback, but
doesn't execute any code.
 The change to the Label's Text property in the Change
Message Button would need to be saved in the view
state.
The Role of View State
 <asp:Label runat="server" ID="lblMessage"
Font-Name="Verdana" Text="Hello, World!">
</asp:Label> <br />
<asp:Button runat="server" Text="Change
Message"
ID="btnSubmit"></asp:Button><br/>
<asp:Button runat="server" Text="Empty
Postback"></asp:Button>

 private void btnSubmit_Click(object sender,


EventArgs e)
{
lblMessage.Text = "Goodbye, Everyone!";
}
Events and
ViewState
The ViewState Property
 Each control is responsible for storing its
own state, which is accomplished by adding
its changed state to its ViewState property.

 The ViewState property is defined in the


System.Web.UI.Control class, meaning that all
ASP.NET server controls have this property
available.

 If you examine the simple properties of any


ASP.NET server control you'll see that the
properties read and write directly to the view
state.
The ViewState Property
 E.g.
 public string Caption
{
get
{
string text = (string) ViewState [“Caption"];
if (text != null)
return text;
else
return string.Empty;
}
set
{
ViewState [" Caption "] = value;
}
}
The ViewState Property
 As this code sample illustrates, whenever a
control's property is read, the control's
ViewState is consulted.

 If there is not an entry in the ViewState, then


the default value for the property is returned.

 When the property is assigned, the assigned


value is written directly to the ViewState.

 The ViewState property is of type


System.Web.UI.StateBag. The StateBag class
provides a means to store name and value
pairs
Timing the Tracking of View State
 The StateBag class has the
TrackViewState() method

 This method is called at the end of the


initialization stage, which happens after
the instantiation stage.

 The StateBag class tracks the changes


to the values of various controls after
TrackViewState() method is invoked
The Cost of View State
 The ASP.NET view state imposes two performance
hits whenever an ASP.NET Web page is requested:
 On all page visits, during the save view state stage the Page
class gathers the collective view state for all of the controls
in its control hierarchy and serializes the state to a base-64
encoded string.

 Similarly, on postbacks, the load view state stage needs to


deserialize the persisted view state data, and update the
controls in the control hierarchy.

 The __VIEWSTATE hidden form field adds extra size to the


Web page that the client must download.

 For some view state-heavy pages, this can be tens of


kilobytes of data, which can require several extra seconds
(or minutes!) for modem users to download.

 Also, when posting back, the __VIEWSTATE form field must


be sent back to the Web server in the HTTP POST headers,
thereby increasing the postback request time.
Disabling the View State
 As a page developer, you can specify that a control
should not save its view state or the view state of its
children controls by setting the control's
EnableViewState property to False (the default is
True).

 The EnableViewState property is defined in the


System.Web.UI.Control class, so all server controls
have this property, including the Page class.

 You can indicate that an entire page's view state need


not be saved by setting the Page class's
EnableViewState to False.

 This can be done either in the code-behind class with


Page.EnableViewState = false; or as a @Page-level
directive—<%@Page EnableViewState="False" %>.
Disabling the View State
 Not all Web controls record the same amount
of information in their view state.

 The Label Web control, for example, records


only programmatic changes to its properties,
which won't greatly impact the size of the
view state.

 The DataGrid, however, stores all of its


contents in the view state.

 For a DataGrid with many columns and rows,


the view state size can quickly add up!
Disabling the View State
 The DataGrid stores its contents in the view state so
the page developer doesn't need to rebind the
database data to the DataGrid on each and every
page load, but only on the first one.

 The benefit is that the database doesn't need to be


accessed as often.

 If, however, you set a DataGrid's EnableViewState


property to False, you'll need to rebind the database
data to the DataGrid on both the first page load and
every subsequent postback.

 For a Web page that has a read-only DataGrid, you'd


definitely want to set the DataGrid's EnableViewState
property to False.
Specifying Where to Persist the View State
 After the page has collected the view state information for all of
the controls in its control hierarchy in the save view state stage,
it persists it to the __VIEWSTATE hidden form field.

 This hidden form field can, of course, greatly add to the overall
size of the Web page.

 The view state is serialized to the hidden form field in the Page
class's SavePageStateToPersistenceMedium() method during
the save view state stage, and is deserialized by the Page
class's LoadPageStateFromPersistenceMedium() method in the
load view state stage.

 With just a bit of work we can have the view state persisted to
the Web server's file system, rather than as a hidden form field
weighing down the page.

 To accomplish this we'll need to create a class that derives from


the Page class and overrides the
SavePageStateToPersistenceMedium() and
LoadPageStateFromPersistenceMedium() methods.
Specifying Where to Persist the View State
 The view state is serialized and deserialized by the
System.Web.UI.LosFormatter class—the LOS stands
for limited object serialization—and is designed to
efficiently serialize certain types of objects into a
base-64 encoded string.

 The LosFormatter can serialize any type of object that


can be serialized by the BinaryFormatter class, but is
built to efficiently serialize objects of the following
types:
 Strings
 Integers
 Booleans
 Arrays
 ArrayLists
 Hashtables
 Pairs
 Triplets
Parsing the View State
 What is the structure of the Page
class's view state object?

 The view state of a control represents


the view state of that control along with
the view state of all of its children
controls.

 Since the Page class forms the root of


the control hierarchy, its view state
represents the view state for the entire
control hierarchy.
Parsing the View State
 The Page class contains a
SavePageViewState(), which is invoked
during the page life cycle's save view state
stage.

 The SavePageViewState() method starts by


creating a Triplet that contains the following
three items:
 The page's hash code. This hash code is used to ensure that
the view state hasn't been tampered with between
postbacks.
 The collective view state of the Page's control hierarchy.
 An ArrayList of controls in the control hierarchy that need to
be explicitly invoked by the page class during the raise
postback event stage of the life cycle.
Parsing the View State
 The Second item is generated by the Page by calling
the SaveViewStateRecursive() method, which is
defined in the System.Web.UI.Control class.

 SaveViewStateRecursive() saves the view state of the


control and its descendents by returning a Triplet
with the following information:
 The state present in the Control's ViewState StateBag.
 An ArrayList of integers. This ArrayList maintains the
indexes of the Control's child controls that have a non-null
view state.
 An ArrayList of the view states for the children controls. The
i th view state in this ArrayList maps to the child control
index in the i th item in the ArrayList in the Triplet's Second
item.
Protecting the View State from
Modification
 A simple means to protect against this sort of tampering is to
use a machine authentication check, or MAC.

 Machine authentication checks are designed to ensure that the


data received by a computer is the same data that it transmitted
out—namely, that it hasn't been tampered with.

 With ASP.NET view state, the LosFormatter performs a MAC by


hashing the view state data being serialized, and appending this
hash to the end of the view state.

 When the Web page is posted back, the LosFormatter checks to


ensure that the appended hash matches up with the hashed
value of the deserialized view state.

 If it does not match up, the view state has been changed en
route.
Protecting the View State from
Modification
 By default, the LosFormatter class applies the MAC.

 You can, customize whether or not the MAC occurs by setting


the Page class's EnableViewStateMac property.

 The default, True, indicates that the MAC should take place; a
value of False indicates that it should not.

 You can further customize the MAC by specifying what hashing


algorithm should be employed.

 In the machine.config file, search for the <machineKey>


element's validation attribute.

 The default hashing algorithm used is SHA1, but you can


change it to MD5 if you like.
Encrypting the View State
 Ideally the view state should not need to be
encrypted, as it should never contain
sensitive information.

 If needed, however, the LosFormatter does


provide limited encryption support.

 The LosFormatter only allows for a single


type of encryption: Triple DES.

 To indicate that the view state should be


encrypted, set the <machineKey> element's
validation attribute in the machine.config file
to 3DES.
Encrypting the View State
 In addition to the validation attribute, the <machineKey> element
contains validationKey and decryptionKey attributes, as well.

 The validationKey attribute specifies the key used for the MAC;
decryptionKey indicates the key used in the Triple DES
encryption.

 By default, these attributes are set to the value


"AutoGenerate,IsolateApp," which uniquely autogenerates the
keys for each Web application on the server.

 This setting works well for a single Web server environment, but
if you have a Web farm, it's vital that all Web servers use the
same keys for MAC and/or encryption and decryption.

 In this case you'll need to manually enter a shared key among


the servers in the Web farm.
Few other Page methods
 Page_Error
 Page_AbortTransaction
 Page_CommitTransaction
Caching
 Caching is the process of storing
frequently used data, usually data that
is costly to generate, for reuse.
 Typically this data is stored in memory
since retrieving data from memory is
much more efficient than retrieving the
data from other locations, such as a
database.
Caching Example
 A catalog used on an e-commerce site might only
change once a week.

 .NET Web application could be built that provides a


front-end interface for that catalog, allowing
customers to purchase products.

 When a customer is simply browsing the catalog, the


system is making (in most cases) network calls to a
back-end database server.

 The database server is also doing calculations on the


data, such as a join query, and returning results.

 This type of configuration is quite common, be it a


catalog or some other type of commonly requested
data from a database.
Caching Example
 However, the design in the above example can be
improved upon.

 We know that the data in the database only changes


once a week, and we know that there are several
performance costs associated with retrieving the data

 Executing of the ASP.NET code to make the database


request.

 Use of the network for the Web server to


communicate with the database server.

 Work done on the database server to compile and


execute the query (or simply execute stored
procedure).
Caching
 Caching is an extremely important technique
for building high-performance, scalable
server applications.

 Some items that are expensive to construct


can be built once and then used for some
amount of time before they are considered
invalid.

 These items are stored in memory where they


can be efficiently retrieved and used without
incurring the cost of reconstructing them.
Caching
 ASP.NET includes three caching
features:
 Output Caching
 Fragment Caching
 Cache APIs / Data Caching
Output / Page Caching
 Output caching allows you to store the
results that a dynamic page generates.

 On subsequent requests, the cached


output is used to satisfy the request
rather than dynamically executing the
page code.

 Output caching is also referred to as


page caching
Output / Page Caching
 Output from any given response is not
cached unless the response is explicitly made
cacheable.

 To be eligible for output caching, a given


page response must have a valid expiration or
validation policy and public cache visibility,
which can be set in either of two ways:
 at design time, by declaratively using the
@ OutputCache directive, or
 at run time, by programmatically using the
HttpCachePolicy class that is exposed via the
Response.Cache object.
Output / Page Caching
 When output caching is enabled, an output cache entry
containing the dynamically generated page response is
created on the first request to the page.

 Subsequent requests are then served from this output


cache entry until the cached response duration expires.

 Once the duration for the cached page expires, the next
request is handled explicitly and causes a dynamically
generated response.

 This response is cached again for the given duration.


Output / Page Caching
<%@ Page Language="VB" %>
<%@ OutputCache Duration="30" VaryByParam="*"
%>
<script runat =server>
Public Sub Page_Load()
Response.Write (DateTime.Now.ToString())
End Sub
</script>
Setting Expirations for Page Caching
 To add a page to the output cache, you
must establish an expiration policy for
that page.

 You can set cache expiration


( or duration )
 declaratively by using the @OutputCache
directive, or
 programmatically by using the
Response.Cache.SetExpires method.
Set output-cache expirations for a
page declaratively
• Include an @ OutputCache
directive at the top of the .aspx file
that you want to output cache.

• The directive must include:


 a Duration attribute that sets the number of
seconds the page output is to be cached,
and
 a VaryByParam attribute that sets which
versions of the page output can be cached,
used mainly for pages that can return
different responses.
Set output-cache expirations for a
page declaratively
 <%@ OutputCache Duration=60
VaryByParam="none" %>

 The Duration and VaryByParam


attributes are both required and an error
is returned if either is omitted. If you
have no need to use the functionality
offered by VaryByParam, set its value to
None.
To set output-cache expirations for a
page programmatically
• In the page's code declaration block, or
in the code-behind class for the page,
include code that sets the expiration
policy for the page using the
Response.Cache.SetExpires method.

• The following example sets a 60-second


expiration for the page, in the same way
the @ OutputCache directive does in
the above example.
To set output-cache expirations for a
page programmatically
 Response.Cache.SetExpires
( DateTime.Now.AddSeconds ( 60 ) );

 When using the @ OutputCache


directive, ASP.NET translates the
specified directive attributes into ( and
automatically invokes ) the
corresponding Response.Cache
methods at run time.
Setting the Cacheability of a Page
 To add a page to the output cache, you must
also establish public cacheability for that
page.

 The cacheability of a Web page defines what


Internet devices a document can be cached
on.

 These devices include the client making the


request, the Web server responding to the
request, and any other cache-capable devices
that may be present along the request or
response stream, such as proxy servers.
Setting the Cacheability of a Page
 When a Web server sends a response, it
passes a Cache-Control HTTP header that,
specifies how documents are to be cached on
the network.

 Depending on the needs of the application,


you may choose to define which devices can
and cannot cache specific pages.

 For example, you may need to use different


cacheability settings for a user logon page
and for a page that displays a selection of
products from a catalog.
Setting the Cacheability of a Page
 For security reasons, you should cache the
page in the former case only on the server,
while the page in the latter scenario can, in all
likelihood, be cached on any cache-capable
device.

 You can set the cacheability of a page's


output declaratively using the
@OutputCache directive, or programmatically
using the Response.Cache.SetCacheability
method.
Set a page's cacheability declaratively
 Include an @ OutputCache directive in
the .aspx file and define the required
Duration and VaryByParam attributes.

 Include a Location attribute in the


directive, the possible values of which
can be Any, Client, Downstream,
Server, or None.

 <%@ OutputCache Duration=60


VaryByParam="none"
Location="Any"%>
Set a page's cacheability declaratively
 If not specified, the default value for the Location
attribute is Any, meaning the page output can be
cached on all cache-capable network
applications that are involved in the response.

 These include the requesting client, the origin


server, and any proxy servers through which the
response passes.

 The @ OutputCache directive sets the Cache-


Control header to Public by default.
Set a page's cacheability programmatically
 If you set expirations for a page
programmatically, though, you must explicitly
set the Cache-Control header to Public using
the Response.Cache.SetCacheability method.

• In the page's code-declaration block or code-


behind class file, include code that sets the
cacheability for the page using the
Response.Cache.SetCacheability method, the
possible values of which can be NoCache,
Private, Public, and Server.

• Response.cache.SetCacheability
(HttpCacheability.Public))
Caching Multiple Versions of a Page
 Often, an application may have a Web page
that can receive different requests for
different information that will be rendered on
the same page; hence, the presentation of the
information will mostly be changed for each
request.

 For example, if a page is meant to allow users


to provide different sets of inputs to a
database query, the page response can be
different for each request.

 So, depending on the purpose, a single


ASP.NET page can generate a number of
possible responses.
Caching Multiple Versions of a Page
 This requires a slightly different approach from that
of output caching pages that do not vary in content.

 Fortunately in ASP.NET, you can simply choose to


cache any or all of the possible versions of a page's
output.

 Basically, ASP.NET allows caching multiple versions


of a page response in either of two ways:
 at design time, by declaratively using variable attributes on
the @ OutputCache directive, or
 at run time, by programmatically using the corresponding
properties and methods of the Response.Cache class.
Caching Multiple Versions of a Page

 Specifically, the @OutputCache directive


includes three attributes that allow you to
cache different versions of page output:
 The required VaryByParam attribute enables
varying the cached output depending on the GET
or POST parameters passed with the request.
 The VaryByHeader attribute enables varying the
cached output depending on the HTTP header
associated with the request.
 The VaryByCustom attribute enables varying the
output cache by browser type or by a custom
string that you define.
Caching Multiple Versions of a Page
 Alternatively, the Response.Cache object
provides two properties and a method
that allow you to do the same things
that the @ OutputCache attributes do,
programmatically.
 The Response.Cache.VaryByParams
property
 The Response.Cache.VaryByHeaders
property
 The Response.Cache.SetVaryByCustom
method
The VaryByParam Attribute
 ASP.NET pages that are used to gather
information from users can generate different
page responses, depending on the user input
that are passed along with the request.

 In HTTP, user input is typically sent to the


server as a collection of name=value
parameters, either in the request URI ( GET )
or in the HTTP request message ( POST ).

 As such, ASP.NET implements the caching of


multiple versions of a page based on these
parameters.
The VaryByParam Attribute
 You can choose to cache page responses that
are associated with a given parameter name,
or all of the possible responses that a page
can generate.

 This is accomplished in either of two ways:


 at design time, by declaratively setting the
VaryByParam attribute of the @
OutputCache directive to the parameter name you
need to cache, or
 at run time, by programmatically setting the
Response.Cache.VaryByParams property.
Specifying output-cache versions for a
page declaratively
 <@ OutputCache Duration=300
VaryByParam="category" >

 VaryByParam enables caching of


multiple page responses that are
generated based on the varying values
of the given parameter ( ex.
category=Camping, category=Climbing,
category=Clothing ), which are then
used to satisfy subsequent similar
requests until the specified cache
duration expires.
Specifying output-cache versions for a
page declaratively
 You can set this attribute to none,
* ( all ), a single parameter, or to a list
of parameters separated by semicolons,
that must correspond to named
parameters sent with the request.

 When set to multiple parameters, the


output cache will contain different
versions of the page for each specified
parameter, each version varying by the
parameter's value.
Specifying output-cache versions for a
page declaratively
 The server ultimately decides if, and for
how long, specified items remain in the
cache.

 When system memory becomes scarce,


as when processing a high volume of
requests, the cache automatically
removes items to free up memory.
Output Caching with Variable GET
Parameters
 The following example illustrates using
VaryByParam with GET parameters, and
shows how different name=value pairs
passed along in the request query string are
used to store and subsequently retrieve
cached responses.
 <table cellpadding=5>
<tr><td>
<a href="varybyparam_get.aspx?
category=Camping">Camping</a></td> <td>
<a href="varybyparam_get.aspx?
category=Climbing">Climbing</a></td> <td>
<a
href="varybyparam_get.aspx?
category=Clothing">Clothing</a></td>
Output Caching with Variable GET
Parameters
 Recall that when a form is submitted using,
the name=value pairs are appended to the
request URI and exposed on the server via the
Request.QueryString collection.

 When the user selects a category ( by clicking


on a hyperlink ), the query string's value that
is passed in the URI becomes accessible, in
this case, via the
Request.QueryString[ "category" ] object.

 The page then constructs the appropriate


database query and shows products
belonging only to the selected category,
using this value.
Output Caching with Variable GET
Parameters
 Note that the first time the user
requests any given category, the page
generates a timestamp indicating when
the response for each request
parameter is first generated.

 Thereafter, subsequent requests for


that category within the cache duration
are served from the output cache, as
indicated by the same timestamp on the
page.
Output Caching with Variable POST
Parameters
 The following example illustrates using the
VaryByParam attribute with form POST
parameters instead.

 The Web page is set up to allow the user to


selectively query for products in various
categories.

 The categories in this case, though, are used


to populate an <asp:dropdownlist> control
that is set to automatically post back ( to the
same page ) when the user makes a selection.
Output Caching with Variable POST
Parameters
 Recall that when a form is submitted
using POST, the name=value pairs of all
controls within the form are passed
along in the HTTP request message and
exposed on the server via the
Request.Form collection.

 When the user selects a category from


the dropdownlist, the control's value
becomes accessible, in this case, via
the Request.Form [ "productType" ]
object.
Output Caching with Variable POST
Parameters
 The page then constructs the
appropriate database query and shows
products belonging only to the selected
category, using this value.

 In the same manner, the responses that


vary by the given parameter are each
added to the output cache, and used to
satisfy subsequent requests until the
cached responses expire.
The VaryByHeader Attribute
 The VaryByHeader attribute allows you
to vary page output caching dependent
on each HTTP header that is passed to
the page in a request.

 You can set this attribute to a single


header, or to a list of headers separated
by semi-colons.

 Depending upon the header or


combination of headers you choose,
multiple versions of a page's output is
cached.
The VaryByHeader Attribute
 In the following example, including the @
OutputCache directive varies the output
cache content by the Accept-Language HTTP
header.

 <%@ OutputCache Duration=300


VaryByHeader="Accept-Language" %>

 Four requests arrive for the page with the


following Accept-Language headers.
 de-lu
 en-us
 Fr
 en-us
The VaryByHeader Attribute
 Since the second and fourth requests have the same
Accept-Language HTTP header values, only the
response generated for one of those requests is
cached.

 The other two Accept-Language values generate page


output versions that are each cached, so a total of
three documents are rendered and cached for these
four requests.

 Any further requests for the page with the same


Accept-Language values are satisfied from the output
cache until the cached page expires ( in this case,
after 300 seconds ).

 This example demonstrates how to output cache


globalized content, depending upon the locale
settings for the requesting browser.
The VaryByCustom Attribute
 The VaryByCustom attribute uses either the
browser type or other custom strings to
output cache multiple versions of a page.

 When you include <%@ OutputCache


Duration=300 VaryByCustom="browser" %>
at the top of your page, you instruct the
output cache to cache varying versions of the
page according to the information provided
by the page's Request.Browser.Type property
( browser name and major ID ).

 If an Internet Explorer browser and a


Netscape Navigator 4.0 browser each request
a page that you include this directive in, an
entry is added for each in the output cache.
The VaryByCustom Attribute

 You can also use this attribute to extend the


functionality of the output cache.

 To do this, you must include a custom string


in the VaryByCustom attribute in the @
OutputCache, and then override the
HttpApplication.GetVaryByCustomString
method in your application's Global.asax file.

 The code that you write in your override


statement defines what the output cache
varies by.
The VaryByCustom Attribute
 In the following directive, the custom string is
defined as Frames.

 <%@ OutputCache Duration=300


VaryByCustom="Frames" %>

 In your application's Global.asax file, you can


include the following code to specify to the
output cache whether the requesting browser
supports frames, and if it does, instruct it to
store a version of the page output in the
cache.
Fragment Caching
 Caching different portions of a single page.

 Enables subsequent requests for a given


portion of a page to be satisfied from the
cache so the code that initially generates that
portion of the page does not have to be run
upon subsequent requests.

 Fragment caching is suitable when you


expect to return the same information in the
same format in certain portions of the page.
Fragment Caching
 Fragment caching is useful when you
need to cache only a subset (parts) of a
page.
 This is accomplished by caching the
outputs of a user control.
 Navigation bars, headers, and footers
are good candidates for fragment
caching.
Fragment Caching
 To use fragment caching, you identify
the parts associated with the request
that use up significant server resources
to create, such as database queries,
and isolate these from the rest of the
page.
 You can then choose which parts of the
page are to be declared for caching, and
allow the rest of the page to be
generated dynamically for each request.
Fragment Caching
 To accomplish this, you must develop a
Web Forms user control ( also known
as a pagelet ) for each portion of the
page that you intend to cache, and
include an @ OutputCache directive in
the user control file ( the .ascx file )

 For example, if you include the


following directive at the top of a user
control file, a version of the user control
is stored in the output cache for 60
seconds.
Fragment Caching
 Note that only the user control is
cached by doing so.

 You can include an output cache


directive in a user control that is inside
an output cached page, or in a user
control that is part of another output
cached user control.

 This provides a powerful composition


model that enables cached pages or
regions to be composed of further
subcached regions.
Adding an ID Attribute to an Output Cached User
Control

 You can include an ID attribute in a user


control tag that you have specified for
output caching in order to program
against that instance of the user
control.

 However, you must explicitly verify the


existence of the user control in the
output cache so that the code will work
properly.
Adding an ID Attribute to an Output Cached User
Control

 For example, if you declaratively assign an id


to a user control ( id="myUserControl" ), you
can check for its existence with the following
code in the containing .aspx file's code
declaration block.
 Sub page_load (sender as Object, e as
EventArgs)
If myUserControl <> null then
‘logic
end if
end sub
Common Mistakes Using Fragment
Caching
 If you write code to manipulate a user control that
contains an @ OutputCache directive, an error will
occur.

 A user control that is output cached is only


dynamically generated for the first request; any
subsequent requests are satisfied from the output
cache until the control expires.

 Any programmatic manipulation that must occur to


create the content of the user control must be
included in the control.

 You can include this logic in one of the page lifecycle


events associated with the user control, such as in
the Page_Load event or Page_PreRender event.
Caching Multiple Versions of User Control
Output
 Just as you can cache multiple versions of a
page's output, you can also cache any or all
possible versions of a user control's output
on any given Web page.

 There are some differences, though, between


adding user control output to the cache and
doing the same for the page.

 While both support multiple response caching


based on HTTP GET and POST parameters,
user controls do not support caching based
on HTTP headers or custom strings.
Caching Multiple Versions of User Control
Output
 Basically, ASP.NET allows caching
multiple versions of user control output
in either of two ways:
 at design time, by declaratively using
variable attributes on the @ OutputCache
directive ( in the .ascx file ), or
 at run time, by programmatically using the
corresponding properties of the
PartialCachingAttribute class ( when you
develop the user control in a code-behind
class ).
Caching Multiple Versions of User Control
Output
 Specifically, the @OutputCache
directive includes two attributes that
allow you to cache different versions of
user control output, both based on GET
query string or form POST parameters:
 the VaryByParam attribute, and
 the VaryByControl attribute.

 You can use either VaryByParam or


VaryByControl depending on the need.
You do not need to include both
attributes in the directive.
Caching Multiple Versions of User Control
Output
 Alternatively,the PartialCachingAttribute
class provides two properties that allow
you to do the same thing by adding an
attribute to a user control in a code-
behind class.
 PartialCachingAttribute.VaryByParams
property
 PartialCachingAttribute.VaryByControls
property
Caching Multiple Versions of a User
Control, Based on Parameters
 Caching multiple versions of user control
output based on parameters will only work if
the user control posts back and processes
the postback in the .ascx file itself.

 You cannot post back to the containing .aspx


page for this type of caching to function
properly.

 In the following sections, we take a closer


look at the different ways of accomplishing
this.
Cache multiple versions of a user control
declaratively by using the VaryByParam
attribute
 Create a user control that posts back.

 Include an @ OutputCache directive in the. ascx file


with the required Duration and VaryByParam
attributes.

 Set the VaryByParam attribute to the user control


name and the GET or POST parameter that you need
to vary the user control output by, separated by a
colon ( : ).

 <%@ OutputCache Duration="300"


VaryByParam="myCtrl:bookType" %>
To cache multiple versions of a user control
programmatically by using the VaryByParams
property
 In a code-behind class, create a user control
that posts back.

 Include a metadata PartialCaching attribute at


the beginning of the user control code.

 Include a value for the Duration attribute and


set the VaryByParams attribute to the user
control name and the GET or POST parameter
that you need to vary the user control output
by.
To cache multiple versions of a user control
programmatically by using the VaryByParams
property
 When included before the code that extends
the UserControl class, the following example
sets Duration to 300 seconds and
VaryByParams to myCtrl:bookType.

 <Partialcaching (300, myCtrl:bookType, null,


null)>
To cache multiple versions of a user control declaratively
by using the VaryByControl attribute

 Create a user control that posts back.


 Include an @ OutputCache directive in the
.ascx file with the required Duration and
VaryByControl attributes.
 Set the VaryByControl attribute to the name
of the GET or POST parameter that you need
to vary the user control output by.
 <%@ OutputCache Duration=300
VaryByControl="bookType" %>
To cache multiple versions of a user control
programmatically by using the VaryByControls property

 In a code-behind class, create a user control


that posts back.
 Include a metadata PartialCaching attribute at
the beginning of the user control code.
 Include a value for the Duration attribute and
set the VaryByControls attribute to the GET
or POST parameter that you need to vary the
user control output by.
To cache multiple versions of a user control
programmatically by using the VaryByControls property

 When included before the code that extends


the UserControl class, the following example
sets Duration to 300 seconds and
VaryByControls to bookType.
 <Partialcaching (300, null, bookType, null)>
Caching Multiple Versions of a User Control by Using
Declarative Attributes
 You can cache multiple versions of a user
control by simply declaring it in a .aspx file
more than once.

 In order to avoid clashing instances of the


control on the page at the same time, you
must include a String property in the user
control code.

 Additionally, you must declare this property


and its value as an attribute in the custom
server control element that you use to include
the user control in the .aspx file.
Caching Multiple Versions of a User Control by Using
Declarative Attributes

 For example, if you create a user


control with a category property, you
need to declare category as an attribute
on the user control tag.
 Assign the attribute a value that is
meaningful to your purposes.
To cache multiple versions of a user
control by using declarative attributes
 In the code-declaration block of an
.ascx file, or in the code-behind class
for the user control, create a String
property.
 This is in addition to any other user
control code you plan to include.
 Using either the @ OutputCache
directive in an .ascx file or the
PartialCachingAttribute in the code-
behind class, specify the output cache
settings for the user control.
To cache multiple versions of a user
control by using declarative attributes
 Include multiple versions of the user control
in a page, including the property you defined
in the class as an attribute in the element.
Make sure the property values are unique on
the page.
 For example, you can include the following
user control tags in the containing .aspx file
with the custom Category attribute.
 <MyUserControl:Menu Category="LeftMenu"
runat="server" />
 <MyUserControl:Menu Category="RightMenu"
runat="server" />
To cache multiple versions of a user
control by using declarative attributes
 <%@ OutputCache Duration="120" VaryByParam="None" %>
<%@ Import Namespace="System.Data" %>
<%@ Import
Namespace="System.Data.SqlClient" %>
<script language="VB" runat="server">
Dim Category As String
Sub Page_Load ( sender As Object, e As EventArgs )
Dim MyConnection As SqlConnection
Dim MyCommand As SqlDataAdapter
Dim ds As DataSet
MyConnection = New SqlConnection ( "server= ( local )
\NetSDK;database=pubs;Trusted_Connection=yes" )
MyCommand = New SqlDataAdapter ( "select * from Authors",
MyConnection )
ds = New DataSet ( )
MyCommand.Fill ( ds, "Authors" )
MyDataGrid.DataSource=new DataView ( ds.Tables ( 0 ) )
MyDataGrid.DataBind ( )
To cache multiple versions of a user
control by using declarative attributes
 <asp:datagrid id="MyDataGrid"
runat=server/>
 Simply including the @ OutputCache
directive with a valid duration value in
the .ascx file allows varied cache output
of this user control.
Cache APIs – Caching Application Data

 Cache Application Programming


Interfaces (APIs) allow you to
programmatically store arbitrary objects
to memory so that your application can
save the time and resources that it
takes to re-create them.
 Cache APIs allow you to expire items
from the cache based on the following
credentials:
 Time
 File dependencies
 Cache key dependencies
Caching Application Data
 This caching mechanism is
implemented via the Cache class, an
instance of which exists for each
application configured on a Web server.
 The ASP.NET cache is private to each
Web application, and its lifetime
depends on the start and end of any
given application.
Caching Application Data

 This means that only pages within an


application domain can have access to
its cache.
 When the application starts, an instance
of the application's Cache object is
created.
 When the application ends, its cache is
cleared.
Caching Application Data

 The application cache provides a simple


dictionary interface using key=value
pairs that allow programmers to easily
store and retrieve objects from the
cache.
 In the simplest case, placing an item in
the cache is just like adding an item to a
dictionary:
 Cache (“mykey”) = myValue
 myValue = Cache (“mykey”)
Caching Application Data
 While the Cache class offers a simple
interface for setting and getting cache items,
it also offers powerful features that allow you
to customize how items are to be cached and
how long they remain available in the cache.
 For example, when system memory becomes
scarce, the cache automatically removes
seldom used items to free up memory to be
able to process a high volume of requests.
 Called scavenging, this technique is one of
the ways that the cache ensures that data that
is not current does not waste valuable server
resources.
Caching Application Data
 You can instruct the cache to give
certain items priority over other items
when it performs scavenging.
 To indicate that a specific item is of
greater or lesser importance than
another, specify one of the
CacheItemPriority enumeration values
when you add an item using the Cache.
 Add method or Cache.Insert method.
 The CacheItemPriority enumeration
specifies the relative priority of items
stored in the cache.
Caching Application Data

 You can also establish an expiration


policy for an item when you add it to the
cache using the Add method or Insert
method.
 You can define the lifetime for an item
by setting the absolute expiration
parameter, which is of type DateTime.
 This allows you to specify the time the
item will expire.
Caching Application Data
 Cache.Insert ( "myData", Source, null,
DateTime.Now.AddHours(1),
TimeSpan.Zero );
 You can also set the sliding expiration
parameter, which is of type TimeSpan.
 This allows you to specify the time to
elapse before the item expires, based
on the time it is accessed.
 Once an item expires, it is removed
from the cache.
Caching Application Data

 Attempts to retrieve its value will return


null unless the item has been added to
the cache again.
 For volatile items that are stored in the
cache, such as those that have regular
data refreshes or those that are valid for
only a set amount of time, set an
expiration policy that keeps those items
in the cache as long as their data
remains current.
Caching Application Data
 For example, if you are writing an application
that tracks sports scores by obtaining the
data from a frequently updated Web site, you
can cache the scores for a game for as long
as those scores do not change on the source
Web site.
 In this case, you can set an expiration policy
that is based on how often the Web site
updates the scores.
 You can write code that determines if an up-
to-date score is in the cache.
 If the score is not up to date, the code should
update the score from the source Web site.
Caching Application Data
 Finally, ASP.NET allows you to define
the validity of a cached item based on
an external file, a directory, or another
cached item.
 These are called file and key
dependencies.
 If a dependency changes, the cached
item is invalidated and removed from
the cache.
 You can use this technique to remove
items from the cache when their data
source changes.
Caching Application Data
 For example, if you write an application that
processes financial data from an XML file and
renders it in a graph, you can insert the data
from the file in the cache and maintain a
dependency on that XML file.
 When the file is updated, the item is removed
from the cache, your application rereads the
file, and a new version of the item is inserted.
 The cache has no information about the
contents of the items it contains.
 It merely holds a reference to those objects,
and provides the means to track their
dependencies and set expiration policies.
Adding Items to the Cache

 There are three different techniques you


can use to add an item to the Cache
object.

 Depending on the requirements of your


application, your choices can range
from the simple to the complex.
To add an item to the cache specifying its
key and value
• You can add items to the cache as you would
add items to a dictionary, by specifying the
item's key and value.
• The following code adds the contents of a text
box to the cache.
 Cache ( "myText" ) = myTextBox.Value ]
 However, if you want to take advantage of the
scavenging, expiration, and dependency
support offered by the cache, you must use
either the Cache.
 Insert method or the Cache.Add method.
 These methods have the same signatures, but
the Add method returns an object that
represents the cached item.
To add items to the cache using the Insert
method
• The Insert method is overloaded, allowing you
to define values for the parameters of the
version that you are using.
• For example, to add only an item key and
value, use the following code.
 Cache.Insert ( "myData",connectionString );
To add items to the cache using the Add
method
• The Add method has the same signature as
the Insert method, but returns an object
representing the item you added.
 Cache.Add ( "myData", connectionString )
 Both of these methods offer a great deal of
control over the conditions under which the
item remains in the cache.
 Both support making the cached item
dependent on external files or directories,
other keys within the cache, or arrays of
either, as explained in the following section.
Adding cache items that have a
dependency
 Adding an item to the cache with a cache
dependency creates an instance of the
CacheDependency class, which tracks
changes to the dependencies you define.
 If any of these dependencies change,
including being deleted or moved, the item
they are associated with is removed from the
cache.
To add an item to the cache that has a
dependency
• You can add an item to the cache with a
dependency by using the dependencies
parameter in the Add or Insert method.
• The following example demonstrates using
the Insert method to add an item to the cache
with a dependency on an XML file.
• Cache.Insert ( "myData", connectionString,
new CacheDependency ( Server.MapPath
( \\myServer\myConfig.xml ) ) );
• You can use the Add and Insert methods to
set expiration policies for the item when you
add it to the cache.
To add an item to the cache with expiration
policies
• Simply set the appropriate parameter to its
corresponding field value when you define an
absolute or a sliding expiration.
• You can add an item to the cache with
expiration policies using the
absoluteExpiration parameter and the
slidingExpiration parameter.
• The following code uses the Insert method to
add an item to the cache with an absolute
expiration of two minutes.
• Cache.Insert ( "myData", connectionString,
null, DateTime.Now.AddMinutes ( 2 ),
NoSlidingExpiration );
To add an item to the cache with priority
settings
• You can add an item to the cache with priority
settings using the priority and priorityDecay
parameters on the Add or Insert method.
• The following example uses the Add method to add
an item to the cache with a priority of High and a
priorityDecay of Never.
• Cache.Add ( "myData", connectionString, null,
NoAbsoluteExpiration, TimeSpan.FromSeconds
( 30 ), CacheItemPriority.High,
CacheItemPriorityDecay.Never, null );
• These methods also allow you to notify your
application when the item is removed from the cache,
using the CacheItemRemovedCallback delegate.
To add an item to the cache with expiration
policies
• The following code uses the Insert method to
add an item to the cache with a sliding
expiration of 30 seconds.
• Cache.Insert ( "myData", connectionString,
null, NoAbsoluteExpiration,
TimeSpan.FromSeconds ( 30 ) );
• You can define either an absolute expiration
or a sliding expiration, not both.
• When you define an expiration policy with one
of the parameters mentioned, you must set
the other parameter to zero.
• The Cache class defines two fields that do
this automatically:
• NoAbsoluteExpiration and NoSlidingExpiration.
To add an item to the cache with expiration
policies
 You can also use the Add or Insert method to define
the relative importance of the cached item by
specifying values from the CacheItemPriority and
CacheItemPriorityDecay enumerations.
 These relative priorities help the Web server when it
scavenges to free memory to remove lower priority
items from the Cache before higher priority items.
Web Services
 Web services are a standardized way for one
application to invoke a method of another
application.

 These applications may reside on different


computers that are some way connected, thru
LAN or Internet.

 With Web services you have two actors, a


client and a server.

 The server makes some set of methods


available.
Web Services
 These methods, when called, will perform
some action and/or return some data.

 The client invokes one of the available


methods of the server.

 The methods of a Web service can accept an


arbitrary number of input parameters, and can
optionally return a result.

 The Web services standard spells out in great


detail how a client can invoke a Web service
method from a server.
Web Services
 The fundamental properties of any service
are:
 Medium by which the service is performed,
 medium used is a computer network, such as the Internet
or a LAN.
 The protocol by which the messages are sent to
and from the service, and
 The messages are typically transported a client to a
server using the HTTP protocol.
 The protocol for the message formats.
 The message protocol used by Web services is SOAP.
SOAP, or Simple Object Access Protocol, is an XML-
encoded messaging protocol that is used to marshal the
input parameters and return values of a Web service
method.
Why Web Services?
 There are various technologies like –
RMI, CORBA, COM, DCOM, etc
 But they all have their own limitations
A High-Level View of Web Services
 Web services provide a means for a
client application to invoke a service of
a server application. The challenges
surrounding this process are as
follows:
 How is the service invoked? That is, how does the
client specify the Web service method he wished
to call?

 How are the input parameters serialized? That is,


if the input parameters involve complex data
types, how are these data types represented in the
message?
SOAP
 The answer to these questions are
spelled out in the SOAP specification.
Understanding SOAP
 SOAP is a standard that specifies the format
of messages used in Web services.

 SOAP messages are messages formatted in


XML - the SOAP standard specifies what XML
elements must be present, in what order, and
what data types they can contain.

 A SOAP message is comprised of the


following parts:
 A SOAP Envelope,
 An optional SOAP Header, and
 A SOAP Body
Understanding SOAP
 The SOAP Body and (optional) Header are
contained within the SOAP Envelope

 SOAP Header for simple Web services are


rarely used

 The SOAP Envelope merely consists of the


XML root element, which specifies the
namespaces used in the SOAP message.

 The root element of a SOAP message is


<soap:Envelope>.
Understanding SOAP
 In a Web service interaction there is a
total of two messages:
 SOAP Request - first, the client sends a
SOAP message to the server, invoking
some method.

 SOAP Response - After this method has


executed, the server returns a response,
which includes the return value of the
method.
Understanding SOAP
 For the SOAP Request the SOAP Body
contains the name of the method the
client wishes to call, along with the
method's input parameters.

 The SOAP response message has in the


body, the return value of the method.
(Even if there is no return value, a
message is still sent back if, nothing
else, to verify that the method
executed.)
SOAP Envelope – Client Request
 <soap:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xmlns:soap="http://schemas.xmlsoap.org/soap/envel
ope/">
<soap:Body>
<Add xmlns="Web Service Namespace">
<a>5</a>
<b>8</b>
</Add>
</soap:Body>
</soap:Envelope>
SOAP Envelope – Server Response

 <soap:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xmlns:soap="http://schemas.xmlsoap.org/soap/envel
ope/">
<soap:Body>
<AddResponse xmlns="Web Service Namespace">
<AddResult>13</AddResult>
</AddResponse>
</soap:Body>
</soap:Envelope>
SOAP Request - Response
HTTP Request - Response
Agenda
 Introduction to .NET
 ASP Today
 ASP.NET
 Server Controls
 Data Controls
 ASP.NET Web Applications
 Business Objects
 Web Services
Server Controls
 Simplify Common Tasks
 Forms
 Tables
 Data Display
 Server Side Programming Model
 Automatic Browser Compatibility
 Less Code, Less Complexity
 Extensible
Server Controls
HTML and Server Controls

<div id=“MyDiv” runat=“server”/>


<asp:TextBox id=“txtUserName”
runat=“Server”/>
<asp:button type=“submit”
OnClick="SubmitBtn_Click"
runat="server"/>

 ID – Uniquely Identifies Control


 Runat – Enables Server Side Processing
 OnClick – Identifies Server Side Event Handler
Server Controls
Forms
<script language="C#" runat=server>

void SubmitBtn_Click(Object sender, EventArgs e) {


Response.Write (“Hello” + txtUserName.Text);
}

</script>

 PostBack
 Server Side Object Automatically Populated from
Client Side Controls
Server Controls
Browser Support
 Targets Client on the Fly
<asp:textbox ForeColor=“red”/>

 Style
 Font

 Validation
 Client Side
 Server Side
Server Controls
Validation
 Without Code
 Required Field
 Within Range
 Two Fields Equal (Password)
 Regular Expressions
 Validation Error Messages
 With Code, but Simplified
 Custom Validation
Agenda
 Introduction to .NET
 ASP Today
 ASP.NET
 Server Controls
 Data Controls
 ASP.NET Web Applications
 Business Objects
 Web Services
Data Controls
 Bind to many data sources
 Collections
 Array
 HashTable
 Dictionary
 ADO.NET
 DataReader
 DataSet
 XML
Data Controls
ADO.NET
 Connection
 Command
 DataAdapter
 DataReader
 DataSet
 DataView
Data Controls
ADO.NET

DataSet
Database
Authors
Connection Authors

DataSetCommand
Select … from authors
Data Controls
ADO.NET

DataSet
Database
Authors
Connection Publishers

DataSetCommand
Publishers
Select … from
publishers
Data Controls
ADO.NET

DataSet
Authors DataGrid

Repeater
Publishers
DataList

DataView
Data Controls
DataGrid
 Displays data as a table
 Control over
 Alternate item
 Header
 Footer
 Colors, font, borders, etc.
 Paging
 Updateable
 Item as row
Data Controls
Repeater
 List format
 No default output
 More control
 More complexity
 Item as row
 Not updateable
Data Controls
DataList
 Directional rendering
 Good for columns
 Item as cell
 Alternate item
 Updateable
Agenda
 Introduction to .NET
 ASP Today
 ASP.NET
 Server Controls
 Data Controls
 ASP.NET Web Applications
 Business Objects
 Web Services
ASP.NET Web Applications
 Global ASAX
 Application_OnStart
 Application_OnEnd
 Session_OnStart
 Session_OnEnd
 Session
 Application
ASP.NET Web Applications
Config.Web
 Site Configuration file
 Like an .INI file for your site
 XML format
 Extensible
 Some settings
 Security
 Session
 Localization
 Tracing
 Debugging
ASP.NET Web Applications
Session Variables
 Store state information
 No longer require Cookies
 Share between servers

<sessionstate
inproc="false"
server=“AnotherServer"
port="42424"
/>
ASP.NET Web Applications
DEMO : Cookieless Sessions
 Sessions with cookies
 Config.Web
 Sessions without cookies
Agenda
 Introduction to .NET
 ASP Today
 ASP.NET
 Server Controls
 Data Controls
 ASP.NET Web Applications
 Business Objects
 Web Services
Business Objects
 Problems with ASP and DLLs
 DLLs with .NET
Business Objects
Problems with ASP and DLLs
 DLL Locking
 Page hit
 Shutdown web application
 Shutdown Internet information Server
 Edit in Visual Interdev
 MTS/COM+
 Shutdown package
 Binary compatibility
 Registry
Business Objects
DLLs with .NET
 Not registered
 Placed in ./BIN directory
 Not locked
 Shadow Copy
Agenda
 Introduction to .NET
 ASP Today
 ASP.NET
 Server Controls
 Data Controls
 ASP.NET Web Applications
 Business Objects
 Web Services
Web Services
 The Web today
 How Web services work
Web Services
The Web Today

Purchase courseware

Purchased

Designed for people to browse


Web Services
The Web Today

Purchase Courseware
?

Server to server is a problem


Web Services
What Are Web Services?
 Allow applications to communicate
across the internet
 Platform independent
 Protocol independent
 Synchronous/asynchronous
 Statefull/stateless
 BizTalk®
 ASP.NET
Web Services
Class Courseware
WebMethod
GetPrice
Purchase

.ASMX
Web Services

Testing
Courseware.asmx
Test HTML Page

.ASMX
Web Services

WebServiceUtil
Courseware.asmx?SDL

Service Definition(XML)

Proxy
DLL
.ASMX
Web Services

Register for Course Purchase Courseware

Proxy
DLL
.ASMX
ASP.NET Web Services
DEMO : Web Services
 Web service source
 Testing
 SDL
 Client Proxy creation
 Consuming a Web service

You might also like