You are on page 1of 114

Advanced Web Forms

Mark Sapossnek

CS 594
Computer Science Department
Metropolitan College
Boston University
Prerequisites
 This module assumes that you understand the
fundamentals of
 C# programming
 ADO.NET
 Introduction to ASP.NET and Web Forms
Learning Objectives
 Assorted topics in ASP.NET
 Developing web applications with ASP.NET
Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
IIS
 Internet Information Server
 Microsoft’s web server
 Foundation for ASP.NET
 Runs in inetinfo.exe process
 Also FTP, NNTP, SMTP
 Shared resources
 Default location c:\inetpub\wwwroot
 Internet Services Manager
 A Microsoft Management Console (MMC) snap-in
IIS
Virtual Directories

 Provides a level of indirection from URL to actual


file locations on the server
 For example, the file for the url:
http://myServer/myApplication/foo.asp
could be mapped to the physical location:
d:\myFolder\myAppFolder\foo.asp
Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Create Controls
 Error Handling  Developing Web Forms
Web Applications
 What is a Web Application?
 All resources (files, pages, handlers, modules,
executable code, etc.) within a virtual directory and
its subdirectories
 Configuration files
 Shared data (application variables)
 global.asax
 Scopes user sessions
 A session is a series of web page hits by a single user within
a block of time
 Shared data (session variables)
Web Applications
global.asax

 Located at application root


 Can define and initialize application variables
and session variables
 Specify object to create with class, COM ProgID or
COM ClassID
 Be careful: use of shared objects can cause
concurrency errors or blocking!
<object id="items" runat="server“
scope=“application”
class="System.Collections.ArrayList" />
Web Applications
global.asax

 Can contain user-created code to handle


application and session events (just like ASP)
 Application_OnStart, Application_OnEnd
 Session_OnStart, Session_OnEnd

void Application_OnStart() {
Application["startTime"]=DateTime.Now.ToString();
}
void Session_OnStart() {
Session["startTime"]=DateTime.Now.ToString();
}
Web Applications
global.asax
 Can use code-behind
 Can contain application-level directives
 <%@ Application Description=“This is my app…” %>
 <%@ Application Inherits=“MyBaseClass” %>
 <%@ Application Src=“Global.cs” %>
 Visual Studio.NET uses this
 <%@ Import Namespace=“System.Collections” %>
 <%@ Assembly Name=“MyAssembly.dll” %>
Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
Configuration
 Goal
 Provide extensible configuration for admins &
developers to hierarchically apply settings for an
application
 Solution
 Store configuration data in XML text files
 Format is readable and writable by people and machines
Configuration
 Settings specified in configuration sections, e.g.
 Security, SessionState, Compilation,
CustomErrors, ProcessModel, HTTPHandlers,
Globalization, AppSettings, WebServices,
WebControls, etc.
 Configuration information stored in web.config
It is just a file, no DLL registration, no Registry
settings, no Metabase settings
 <!-- web.config can have comments -->
Configuration
Configuration Hierarchy

 Configuration files can be stored in application


folders
 Configuration system automatically detects changes
 Hierarchical configuration architecture
 Applies to the actual directory and all subdirectories

Root web.config
Dir
Sub
Dir1
Sub
Dir2
Configuration
web.config Sample

<configuration>
<configsections>
<add names=“httpmodules“
type=“System.Web.Config.HttpModulesConfigHandler“/>
<add names=“sessionState“
type=“...“/>
</configsections>

<httpModules>
<!--- http module subelements go here -->
</httpModules>

<sessionState>
<!--- sessionstate subelements go here -->
</sessionState>
</configuration>
Configuration
Configuration Hierarchy

 Standard machine-wide configuration file


 Provides standard set of configuration section
handlers
 Is inherited by all Web Applications on the machine

C:\WINNT\Microsoft.NET\Framework\v1.0.2914\config\machine.config
Configuration
User-defined Settings

 Create web.config in appropriate folder


<configuration>
<appSettings>
<add key=“CxnString”
value=“localhost;uid=sa;pwd=;Database=foo”/>
</appSettings>
</configuration>

 Retrieve settings at run-time


string cxnStr = ConfigurationSettings
.AppSettings["CxnString"];
Configuration
Custom Configuration Handlers

 Extend the set of section handlers with your own


 Implement the interface:
System.Web.Configuration.IConfigurationSectionHandler

 Add to web.config or machine.config


Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
Tracing
 ASP.NET supports tracing
 Easy way to include “debug” statements
 No more messy Response.Write() calls!
 Debug statements can be left in, but turned off
 Great way to collect request details
 Server control tree
 Server variables, headers, cookies
 Form/Query string parameters
 Tracing provides a wealth of information about the page
 Can be enabled at page- or application- level
Tracing
Methods and Properties

 Methods
 Trace.Write: Writes category and text to trace
 Trace.Warn: Writes category and text to trace in red
 Properties
 Trace.IsEnabled: True if tracing is turned on for
the application or just that page
 Trace.Mode: SortByTime, SortByCategory
 Implemented in System.Web.TraceContext class
Tracing
Page-Level Tracing

 To enable tracing for a single page:


1. Add trace directive at top of page
 <%@ Page Trace=“True” %>
2. Add trace calls throughout page
 Trace.Write(“MyApp”, “Button Clicked”);
 Trace.Write(“MyApp”, “Value: ” + value);
3. Access page from browser
Tracing
Application-Level Tracing

 To enable tracing across multiple pages:


1. Create web.config file in application root
<configuration>
<trace enabled=“true” requestlimit=“10”/>
</configuration>

1. Hit one or more pages in the application


2. Access tracing URL for the application
http://localhost/MyApp/Trace.axd
Tracing
Tracing Demo

 Demo: Trace1.aspx
 Show information obtained from tracing
Tracing
Tracing Into A Component

 To add tracing to a component:


 Import the Web namespace:
using System.Web;
 Enable tracing in your class constructor (optional):
HttpContext.Current.Trace.IsEnabled = true;
 Write to trace:
HttpContext.Current.Trace.Write(“category”,“msg”);
Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
State Management
The Problem

 How/where to store data?


 How can you pass data from page to page?
 How do we get around HTTP statelessness?
State Management
Three-Tier Architecture

Client
Store the data on one or more
of the physical tiers

Web Servers

Data can be
per-user permanent,
per-user (session) or Database
per-application
State Management
Client

 Client-side state management means this:


 Client requests an initial page
 The server generates a HTTP/HTML response that is
sent back to the client
 This response includes data (state)
 User looks at the response and makes a selection,
causing another request to the server
 This second request contains the data that was sent in the
first response
 The server receives and processes the data
 Could be same server or different server
State Management
Client

 URL in a hyperlink (<a>)


 Query string
 Very visible to users
 This can be good or bad
 Hidden form elements
 Like __VIEWSTATE
 Cookies
 Limited to 4K
 May be blocked by users
State Management
Web Server (Middle-Tier)

 Application variables
 Shared by all sessions (users)
 Session variables
 Still need to pass session id through the client
 ASP.NET State Service or database
 Caching
 Similar to application variables, but can be updated
periodically or based upon dependencies
State Management
Database

 Application-level
 Part of application database design
 Session-level
 Custom session state management in database
 ASP.NET database session state support
State Management
In ASP.NET

 ASP.NET supports both Application-level and


Session-level state management
 Allows you to store state (data) in middle tier
State Management
Application Variables
 Application state is stored in an instance of
HttpApplicationState
 Accessed from Page.Application property
 Can lock Application object for
concurrent use
 Needed only when changing application variable
 Again, use this wisely
 Use in “read-mostly” style
 Initialize in global.asa
 Avoid serializing your pages
State Management
Sessions
 What is a session?
 Context in which a user communicates with a server over
multiple HTTP requests
 Within the scope of an ASP.NET Application
 HTTP is a stateless, sessionless protocol
 ASP.NET adds the concept of “session”
 Session identifier: 120 bit ASCII string
 Session events: Session_OnStart, Session_OnEnd
 Session variables: store data across multiple requests
 ASP.NET improves upon ASP sessions
State Management
Session Identifier

 By default, session id stored in a cookie


 Can optionally track session id in URL
 New in ASP.NET
 Requires no code changes to app
 All relative links continue to work
<configuration>
<sessionState cookieless=“true”/>
</configuration>
State Management
Session Variables
 ASP stores session state in IIS process
 State is lost if IIS crashes
 Can’t use session state across machines
 ASP.NET stores session state:
 In process
 In another process: ASP State NT service
 In SQL Server database
<sessionstate inproc="false"
server=“AnotherServer" port="42424" />

<sessionstate inproc="false"
server=“AnotherServer" port="42424"
usesqlserver=“true” />
State Management
Session Variables

 “Live” objects are are not stored in session state


 Instead, ASP.NET serializes objects out between
requests
 ASP.NET approach provides:
 Ability to recover from application crashes
 Ability to recover from IIS crash/restart
 Can partition an application across multiple machines
(called a Web Farm)
 Can partition an application across multiple processes
(called a Web Garden)
State Management
Application & Session Variables

 Demo: ApplicationAndSession.aspx
State Management
Transfering Control Between Pages
 Link to a page
 Postback
 Response.Redirect
 Causes HTTP redirect
 Tells browser to go to another URL
 Server.Transfer
 Like a redirect but entirely on one server
 Server.Execute
 Execute one page from another then return control
 Both pages processed on same server
Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
Caching
 Many sites spend considerable effort generating
the same web pages over and over
 For example, a product catalog changes overnight,
but is accessed tens of thousands of times a day
 Server-side caching can vastly improve
performance and scalability
 ASP.NET provides support for
 Page output caching
 Data caching
Caching
Page Output Caching

 Entire web page output (HTML) is cached


 Must specify life of cached page (in seconds)
<%@ OutputCache Duration="60“ VaryByParam="none" %>

 Can cache multiple versions of a page, by:


 GET/POST parameters; use VaryByParam
 HTTP header; use VaryByHeader
 E.g. Accept-Language
 Browser type or custom string; use VaryByCustom
Caching
Partial Page Output Caching

 Can cache a portion of a page by placing it in


a User Control
 Can cache multiple versions of a User Control
on a page, by property; use VaryByControl
Caching
Caching in the Browser

 Don’t confuse server-side page output caching


with how the browser and proxy servers cache
the page
 Use Response.Cache to specify HTTP cache
headers
 Contains a HttpCachePolicy object
Caching
Data Caching

 Data cache is similar to application variables


 Can cache objects, HTML fragments, etc.
 Usage pattern:
 Try to retrieve data
 If null then create data and insert into cache
DataView Source = (DataView)Cache["MyData"];
if (Source == null) {
Source = new DataView(ds.Tables["Authors"]);
Cache["MyData"] = Source; // Save in cache
}
Caching
Data Caching

 Cache object is stored on the Page and is an


instance of System.Web.Caching.Cache
Caching
Data Caching

 Cache may be scavenged: when memory runs


low it will be automatically reclaimed
 Can specify data expiration: absolute time (e.g.
midnight), relative (in 1 hour)
 Cached data can be dependent upon a file or
other cache item
Cache.Insert("MyData", Source, null, // Expire in 1 hour
DateTime.Now.AddHours(1), TimeSpan.Zero);
Cache.Insert("MyData", Source, // Dependent on file
new CacheDependency(Server.MapPath("authors.xml")));
Caching
Data Caching

 Populating a data cache has an inherent race


condition: if hit almost concurrently, multiple
pages may try to populate the same cache
 This probably doesn’t matter at all; it’s only
significant if the cost to create the data is
prohibitive or if there are side effects
 If it does matter, there are two solutions:
 Populate the cache in Application_OnStart
 Synchronize access to the cache
Caching
Data Caching

private static String cacheSynchronize = "myKey";

DataView Source = (DataView)Cache["MyDataSet"];


if (Source == null) {
lock (cacheSynchronize) {
Source = (DataView)Cache["MyDataSet"];
if (Source == null) { // Have to test again
// Open database ...
Source = new DataView(ds.Tables["Authors"]);
Cache["MyDataSet"] = Source; // Save in cache
}
}
}
Caching
Data Caching
 ASP.NET page state maintenance is great, but
__VIEWSTATE can get quite large
 Why store constant data in __VIEWSTATE?
 E.g. dropdowns listing countries, states, days of the
week, months, product categories, SKUs, etc.
 Instead, set EnableViewState=false, cache
that data on the server, and populate the control
from the cache in Page_Load
 Can cache data or even HTML
 Use Control.Render() to obtain a control’s HTML
Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
Error Handling
 .NET Common Language Runtime provides a
unified exception architecture
 Runtime errors done using exceptions
 VB now supports try/catch/finally
 ASP.NET also provides declarative application
custom error handling
 Automatically redirect users to error page when
unhandled exceptions occur
 Prevents ugly error messages from being sent to users
Error Handling
Custom Error Pages

 Can specify error pages for specific HTTP status


codes in web.config
<configuration>
<customerrors mode=“remoteonly”

defaultredirect=“error.htm”>
<error statuscode=“404”
redirect=“adminmessage.htm”/>
<error statuscode=“403”
redirect=“noaccessallowed.htm”/>
</customerrors>
</configuration>
Error Handling
Error Events

 Can override Page.HandleError to deal with


any unhandled exception on that page
 Global application event raised if unhandled
exception occurs
 Provides access to current Request
 Provides access to Exception object
 See HttpApplication.Error event
Error Handling
Error Event

 What do you actually do when an error occurs?


 Use new EventLog class to write custom events to
log when errors occur
 Use new SmtpMail class to send email to
administrators
Error Handling
Writing to Event Log
<%@ Import Namespace="System.Diagnostics" %>
<%@ Assembly name="System.Diagnostics" %>
<script language="C#" runat=server>
public void Application_Error(object Sender, EventArgs E) {
string LogName = "MyCustomAppLog";
string Message = "Url " + Request.Path + " Error: " +
this.Error.ToString()
// Create event log if it doesn’t exist
if (! EventLog.SourceExists(LogName)) {
EventLog.CreateEventSource(LogName, LogName);
}
// Fire off to event log
EventLog Log = new EventLog();
Log.Source = LogName;
Log.WriteEntry(Message, EventLogEntryType.Error);
}
</script>
Error Handling
Sending SMTP Mail

<%@ Import Namespace="System.Web.Util" %>


<%@ Assembly name="System.Diagnostics" %>
<script language="C#" runat=server>
public void Application_Error(object Sender, EventArgs E) {
MailMessage MyMessage = new MailMessage();
MyMessage.To = "scottgu@microsoft.com";
MyMessage.From = "MyAppServer";
MyMessage.Subject = "Unhandled Error!!!";
MyMessage.BodyFormat = MailFormat.Html;
MyMessage.Body = "<html><body><h1>" + Request.Path +
"</h1>" + Me.Error.ToString() + "</body></html>";
SmtpMail.Send(MyMessage);
}
</script>
Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
Deployment
 XCOPY deployment
 Components are placed in .\bin folder
 No DLL deployment, registration
 Unless you’re using COM or other DLLs
 No locked DLLs
 DLLs are “shadow copied” into a hidden folder
 .aspx files are automatically compiled
 Not true for codebehind
 Update code (.aspx and assemblies) while server
is running
 No need to stop/bounce the server
Deployment
 Applications are isolated
 Each can have their own version of components
 Uninstall = delete /s *.*
Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
Availability
 ASP.NET handles failures in user and
system code
 Detects and recovers from problems
 Access violations, memory leaks, deadlocks
 Supports pre-emptive cycling of apps
 Time and request-based settings
Availability
Process Model Recovery

 ASP.NET runs code in an external worker


process – aspnet_ewp.exe
 Automatic AV/Crash Protection
 It is also now possible to configure ASP.NET
worker process to recover from:
 Memory Leaks
<processmodel memorylimit=“75” />

 Deadlocks
<processmodel requestqueuelimit=“500” />
Availability
Preemptive Recycling

 ASP.NET optionally supports pre-emptive


cycling of worker processes
 Eliminates need for admins to “kick the server”
once a week
 Can be configured two ways:
 Time based (reset every n minutes)
<processmodel timeout=“60” />

 Request based (reset every n requests)


<processmodel
requestlimit=“10000” />
Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
Security
 Reasons for Security
 Prevent access to areas of your Web server
 Record and store secure relevant user data
 Security Configuration
 <security> tag in web.config file
 Authentication, Authorization, Impersonation
 Code Access Security
 Are you the code you told me you are?
 Protect your server from bad code
Security
Authentication

 Who are you?


 Server must authenticate client
 Client should authenticate server
 Kerberos does
 Need a directory to store user accounts
 NT: Security Accounts Manager
 Good for intranet usage up to about 40,000 accounts
 Windows 2000: Active Directory
 Good for intranet and Internet usage
Security
IIS Authentication
 Anonymous
 A single W2K/NT account is used for all visitors
 Basic authentication
 Standard, commonly supported
 Password sent in clear text
 Digest authentication
 Standard, but not yet common
 Integrated Windows Authentication
 NTLM
 Kerberos (Windows 2000 only)
 Client certificates
 Mapped to W2K/NT account
Security
ASP.NET Authentication

 Passport module provided


 Exposes passport profile API
 Custom, forms-based authentication
 Easy to use, with cookie token tracking
 Enables custom login screen (no popup dialogs)
 Supports custom credential checks against database,
exchange, etc.
Security
Authorization
 Now that I know who you are, here’s what you are
allowed to do
 W2K/NT DACLs (Discretionary Access-Control List)
 Grant and deny read/write/execute/etc. permission to users
or groups of users
 IIS also provides coarse-grained control
 Read, write, run script, run executable, directory browsing, script
access for virtual directories, directories and files
Security
ASP.NET Authorization

 ASP.NET supports authorization using either


users or roles
 Roles map users into logical groups
 Example: “User”, “Manager”, “VP”, etc.
 Provides nice developer/admin separation
 Developers can perform runtime role checks in
code
 if (User.IsInRole(“Admin”) { }
Security
Impersonation

 IIS authenticates the “user”


 A token is passed to the ASP.NET application
 ASP.NET impersonates the given token
 Access is permitted according to NTFS settings
Security
Code Access Security

 .NET Framework feature


 Verify the code‘s identity and where it comes
from
 Specify operations the code is allowed to
perform
Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
HTTP Runtime
 The low-level HTTP processing infrastructure
 Logical replacement for ISAPI
 Managed code; runs within an unmanaged host process
 Aims for 100% availability
 Asynchronously processes all requests
 Multithreaded
 Provides ability to replace/customize/extend
the core product
 Eliminate “black box” magic with ASP/IIS
 Support other programming abstractions
HTTP Runtime
 Provides built-in thread pool support
 No private thread pool required
 Provides full access to ASP.NET intrinsics
 Clean object-oriented class APIs
 No more obscure ISAPI programming
 Built-in async execution support
 Enables unwinding of worker threads during the
execution of requests
HTTP Runtime
 ASP.NET has a well-factored, layered architecture
 Developers can hook in at various levels
 Replace or modify built-in functionality
 HttpModules allow intercepting requests
 Similar to ISAPI filter
 Used for authentication, state, output caching
 HttpHandlers allow low-level request handling
 Object implements IHttpHandler
 Activated to handle requests
 Pages and services built on top of IHttpHandler
 Add modules and handlers in web.config
HTTP Runtime
 ASP.NET Web Forms and Web Services built
entirely using the ASP.NET HTTP Runtime
 No “hidden” tricks or escapes
 You could build the same….
HTTP Runtime
 HTTP module pipeline
 Managed classes
 Each module implements a specific interface
 For example: state management or security
 All requests are routed through the same pipeline
 Request handler
 Managed classes
 Multiple request handlers for one application
 But only one per URL
HTTP Runtime
HTTP HTTP HTTP
Handler Handler Handler

Application
HTTP Module Http Context
HTTP Module

HTTP Module

Managed
ASP+ HTTP Runtime code
Native
Host (IIS 5, IIS 4, IE) code
HTTP Runtime
HTTPContext
 HttpContext is an object that encapsulates all
information about an individual Http Request
within ASP+
 System.Web.HttpContext
 HttpHandler and HttpModules access to
ASP.NET intrinsics via HttpContext
 “Flowed” throughout request lifetime
 HttpHandlers and HttpModules can also
“add” objects into HttpContext
 Objects then flowed throughout request
HTTP Runtime
System.Web.HTTPContext
public class HttpContext {
public HttpRequest Request { get; }
public HttpResponse Response { get; }
public HttpServerUtility Server { get; }
public HttpApplication Application { get; }
public HttpSession Session { get; }
public IPrincipal User { get; }
public Cache Cache { get; }
public IDictionary Items { get; }

public IHttpHandler Handler { get; }


public Exception Error { get; }
public DateTime TimeStamp { get; }

public Object GetConfig(String name);


}
HTTP Runtime
HTTPRequest/HTTPResponse

 HttpRequest/HttpResponse objects have


been significantly enhanced
 HttpRequest: 25 new props, 3 methods
 HttpResponse: 9 new props, 7 methods

 Great new additions:


 TextWriter/Stream support
 Filter Stream support
 WriteFile
HTTP Runtime
HttpHandlers

 HttpHandlers enable processing of


individual Http URLs or groups of URL
extensions within an app
 Analogous to ISAPI Extensions
 HTTPHandler examples
 ASP.NET Page Handler
 ASP.NET Service Handler
 Server-Side XSL Transformer
 Image Generator Service
HTTP Runtime
HttpHandlers
 Built as classes that implement the
System.Web.IHttpHandler interface
public interface IHttpHandler {
public void ProcessRequest(HttpContext context);
public bool IsReusable();
}

 ProcessRequest() Method
 Method that processes individual request
 IsReusable() Method
 Indicates whether pooling is supported
HTTP Runtime
HttpHandler Registration
1. Compile and deploy .NET Library DLL within “bin” dir
under application vroot
2. Register HttpHandler in web.config
<configuration>
<httphandlers>
<add verb=“*” path=“foo.bar” type=“assembly#class”/>
</httphandlers>
</configuration>

3. Ensure that HttpHandler file extension is registered


within IIS to xspisapi.dll
 Hint: Copy/Paste “.aspx” registration entry
HTTP Runtime
HttpModules

 HttpModules enable developers to intercept,


participate or modify each individual request into
an application
 HttpModule Examples:
 Output Cache Module
 Session State Module
 Personalization State Module
 Custom Security Module
HTTP Runtime
HttpModules

 Built as classes that implement the


System.Web.IHttpModule interface

public interface IHttpModule {


public String ModuleName { get; }
public void Init(HttpApplication application);
public void Dispose();
}
HTTP Runtime
HttpModules

 HttpModules can use Init() method to sync any


HttpApplication
 Global Application Events
 Per Request Application Events
 Global Application Events
 Application_Start
 Application_End
 Application_Error
HTTP Runtime
Per Request Application Events
 Per Request Events (in order):
 Application_BeginRequest
 Application_AuthenticateRequest
 Application_AuthorizeRequest
 Application_ResolveRequestCache
 Application_AquireRequestState
 Application_PreRequestHandlerExecute
 Application_PostRequestHandlerExecute
 Application_ReleaseRequestState
 Application_UpdateRequestCache
 Application_EndRequest
 Per Request Transmission Events:
 Application_PreSendRequestHeaders
 Application_PreSendRequestContent
HTTP Runtime
HTTP Module Registration

1. Compile and deploy .Net Library DLL within


“bin” dir under app vroot
2. Register HttpModule in web.config
<configuration>
<httpmodules>
<add type=“assembly#classname”/>
</httpmodules>
</configuration>
Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
Targeting Uplevel Clients
 Goal: Pages render more richly to uplevel
clients, but work well in downlevel clients too
 Page developers can identify target client
<%@ Page ClientTarget="Uplevel" %>
<%@ Page ClientTarget="Downlevel" %>
<%@ Page ClientTarget="Auto" %>
Targeting Uplevel Clients
Request.Browser

 Provides more granular control of what is


rendered to a given client
 Exposes specific client capabilities

if (Request.Browser.Frames == True) {
// Use frames
}
Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
Creating Controls
 ASP.NET provides two ways to create your own
server-side controls
 User Controls: Essentially a mini .aspx file
 Formerly called a “Pagelet”
 Custom Controls: You derive a class from
System.Web.UI.Control
Creating Controls
User Controls
 Provide a simple way for page developers to
author controls
 Stored in a .ascx file
 Not just a server-side include
 Enables full encapsulation
 Supports nested controls
 Separate code namespace
 Separate code language
 Can partition work across multiple developers
 Great way to reuse work across multiple pages and
applications
Creating Controls
Registering User Controls

 Registers user control for use on a page

<%@ Register TagPrefix="Acme“ TagName="Message"


Src="pagelet1.aspc" %>

...

<Acme:Message runat="server"/>
Creating Controls
Exposing a User Control Object Model

 User controls can expose object model to pages


 Properties, fields, events, methods
 Just make them public

<script language=“C#" runat="server">


public string Color = "blue“;
</script>

<font color=<%=Color%>>
This is a simple message pagelet
</font>
Creating Controls
Programmatic Use of User Controls

 Page.LoadControl(string source)
 Dynamically instantiates a user control
 Get and customize an instance:
foo = Page.LoadControl("foo.ascx");
foo.color = "red“;

 Insert into the control hierarchy:


myPanel.Controls.Add(foo);
Creating Controls
Custom Controls

 A class that you create


 Derived from System.Web.UI.Control

using System;
using System.Web;
using System.Web.UI;

public class MyControl : Control {


protected override void Render(HTMLTextWriter w) {
w.Write(“<h1>Control output</h1>”);
}
}
Creating Controls
Custom Controls
 Must implement Render() method
 Can expose properties, methods and events
 Should maintain state
 Should handle postback data
 Can generate client-side script to do postback
 Should handle child controls
 Render them
 Handle events
 Can expose and implement templates
 Can handle data binding
Creating Controls
Custom Controls vs. User Controls

User Controls Custom Controls


Good for reuse,
Good for application-specific UI
encapsulate common UI

Easy to build Can be more complex to build

Total flexibility, better


Less flexibility, performance,
performance, and designer
designer support
support

No template support Can support templates


Agenda
 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
Developing Web Forms
Using Notepad

 Incredibly simple: just create .aspx file as a text


file, edit, and hit the page
 That’s how the demos in this module were done
 Use tracing as a debugging aid
Developing Web Forms
Using Visual Studio.NET

 Create a new project


 Choose “Web Application”
 Specify URL of application
Developing Web Forms
IBuySpy

 http://www.ibuyspy.com
Developing Web Forms
Debugging

 Basic Debugger ships with the SDK


 Multi-language
 Single stack trace
 Breaks, watches, etc.
 Visual Studio® Debugger
 Adds remote debugging support
 Supports managed/unmanaged debugging
Developing Web Forms
Debugging

1. Create web.config file in application root


<configuration>
<compilation debugmode=“true”/>
</configuration>

2. Attach using debugger


3. Set breakpoints
4. Hit page or service
Conclusion

 IIS  Deployment
 Web Applications  Availability
 Configuration  Security
 Tracing  HTTP Runtime
 State Management  Targeting Uplevel Clients
 Caching  Creating Controls
 Error Handling  Developing Web Forms
Resources
 Quick Start Tutorial
http://localhost/quickstart/ASPPlus/default.htm
 ASP.NET Overview
http://msdn.microsoft.com/msdnmag/issues/0900/ASPPlus/AS
PPlus.asp
 Caching
http://msdn.microsoft.com/voices/asp04262001.asp
 Session state
http://msdn.microsoft.com/library/default.asp?URL=/libra
ry/welcome/dsmsdn/asp12282000.htm
 Validation
http://msdn.microsoft.com/library/techart/aspplusvalid.h
tm
 Tracing
http://msdn.microsoft.com/library/default.asp?URL=/
library/welcome/dsmsdn/asp01252001.htm
 Thank you

You might also like