You are on page 1of 37

ASP Best

Practices
George V. Reilly
Software Design Engineer
Internet Information Services
Microsoft Corporation

02/09/08 1
ASP Best Practices
 How to build good Active Server Pages
applications, with an eye to robustness,
correctness, maintainability, and
performance.
 What not to do.

02/09/08 2
Agenda
 What is ASP
 Website Design
 3- or 4-Tier Application Design
 Readability, Maintenance, Testing
 Session and Application State
 Caching
 Components
 Performance
 Databases
 New in IIS 5
02/09/08 3
What is ASP?
 Active Server Pages is:
 What Connects the User Interface
(HTML) with Business Logic
 A Consistent, Easy-To-Use Interface to
Web-based Clients that Maintains State
 The Environment for Web Applications
that Require Transactions
 Active Server Pages is not:
 The place to put business logic (use
MTS/COM+ Components or the
database instead)
02/09/08 4
ASP Lessons
Learned
 Use script as glue only
 Developing Applications
 Develop applications, not just stand alone pages
 Caching
 Cache Inputs
 Cache Outputs
 Blocking versus Non-blocking scripts
 Threads per processor
 Benchmark
 Set absolute goals, not just relative goals

02/09/08 5
More ASP Lessons
Learned
 Test before deploying
 Use good components
 Minimize database access
 Cache transformed output

 Defer work (Real Enough Time)


 Latency kills performance

 Using the Message Queue server (MSMQ)

 Benchmark
 Dedicated lab

 Tools

 Methods for performance testing (profiling)

02/09/08 6
Website Design (1
of 3)
 What does your site offer?
 Information Architecture: 80/20 Rule
 Site Navigation
 Page Layout
 Usability
 Accessibility
 use ALT and TITLE attributes
 navigable without images or image maps

 Jakob Nielsen, www.useit.com


02/09/08 7
Website Design (2
of 3)
 Lowest common denominator browser or
DHTML, Java applets, ActiveX, XML,
RDS, … ?
 Screen resolution & color resolution
 WebTV, PocketIE, VGA
 Safe web palette: 6x6x6 colors

 WIDTH and HEIGHT attributes on IMGs

 Non-browser user agents: spiders


 Frames
 Cookies for personalization
02/09/08 8
Website Design (3
of 3)
 Link Rot
 Don’t stagnate
 Get noticed: meta tags
 Proofread the content
 Search Page
 Measure success
 Feedback
 Track Users

 Minimize download times

02/09/08 9
3- or 4-Tier Design
Middle Tier -- ASP

Client Presentation Business Data


Tier Layer Logic Tier

Browsers ASP Components DBMS

02/09/08 10
Readability and
Maintainability
 Use comments
 <% Option Explicit %> for VBScript
 Use string variables for SQL statements =>
easier debugging
 Use Server.MapPath and relative paths
 Use adovbs.inc or <!--METADATA
TYPE=typelib FILE=some.dll-->, not
hardcoded literal constants
 Specify all parameters to ADO so that
defaults don’t cause problems
 Encapsulate code: libaries, components
02/09/08 11
Correctness
 Server.URLEncode
 Error handling
 No nested vroots

02/09/08 12
Internationalization/L
ocalization
 Use <% @codepage %> if using string literals
from codepages other than default codepage for
the machine
 Use Session.CodePage dynamically whenever
DB data accessed in non-default codepage
 (IIS 5) UTF-8 supported for Response.Write only

02/09/08 13
Miscellaneous
 Use fine-grained #includes to factor
and reuse code
 Break queries into Page i of N.

02/09/08 14
Testing
 Proofread the content
 Multiple Browsers
 Stress Testing
 Performance Testing
 Homer, er, Web Application Stress Tool
 IIS Exception Monitor
 WebMeter
 Mutek BugTrapper

02/09/08 15
Monitoring Site
 HTTPMonitor
 Log Analyzers
 WebTrends
 Site Server Express Usage Analyst

02/09/08 16
Securing your
Website
 Validate users
 Validate input
 Don’t use .inc file extension for
#includes. Use .asp, script map .inc, or
secure the directory
 Put .MDBs outside vdirs
 Use ADSI for Security Administration

02/09/08 17
Authentication
 Basic
 Remote nodes
 Auditing?
 Access control?

02/09/08 18
Session State (1 of

2)
Seductively convenient but problematic
 HTTP Protocol is stateless
 Useful for shopping baskets
 Hampers scalability
 Serializes execution, e.g., frames
 Use <% @ EnableSessionState=False %> to
disable sessions on pages that don’t need them
 Disable completely if possible
 Doesn’t scale well to web farms
 Apt-threaded components lock session down to a
single thread => decreases throughput
 Wastes memory
 Fragile: always use same case in URLs
 Session state doesn’t persist to disk
02/09/08 19
Session State (2 of
2)
 Sessions time out
 Requires cookies to be enabled on user’s browser
 Disconnect Recordsets in Session state; don’t
cache connections
 Don’t have empty Session_OnEnd in global.asa
 Alternatives
 Cookies
 Encode state directly => easy, small, insecure
 ID for back-end database (e.g., Site Server Active
User Object)
 Querystring parameters
 Munged URLs (like Amazon)
 Hidden FORM variables
02/09/08 20
Application State
 Useful for shared data
 Non-persistent
 Doesn’t work well in webfarms => only
readonly state useful

02/09/08 21
Process Isolation
 Robustness/performance trade-off
 POOP (Pooled out-of-process) is
default in IIS 5
 IUSR_machinename: in-proc apps
 IWAM_machinename: OOP apps

02/09/08 22
Caching
 Wonderful for static content that doesn’t change
often
 Annoying for really dynamic content
 Transatlantic links often saturated
 Don’t use Response.Expires=0, use negative
number
 Response.Expires = -100000
 (or Response.ExpiresAbsolute=#Jan 1, 1999 00:00:00#)
 Response.AddHeader “Pragma”,”no-cache”
 Response.AddHeader “cache-control”,”no-store”
 Server caching
 Proxy caching
02/09/08
 Client caching 23
Components (1 of
3)
 Performance
 Excessive script
 Scalability
 Isolate Business Logic from ASP
Presentation Layer
 Reuse by ASP and other environments
 Transactions
 Strong Typing
 Access OS features
 Protect Intellectual Property
02/09/08 24
Components (2 of
3)
 Use Server.CreateObject if you need
 MTS Transactions
 Security Context

 ASP intrinsics (Response, Request, etc)

 OnStartPage and OnEndPage

 Otherwise can use CreateObject for


performance (Apt-threaded objects only)
 Use <object runat=server> for delayed
instantiation
 IIS 5: no perf. difference between CO and
S.CO
02/09/08 25
Components (3 of
3)
 Stateless vs. store in
Session/Application
 Stress test components
 Performance test on multiprocessor
systems
 Opportunity for Leaks and other Bugs
 Harder to debug
 Recompilation and reloading

02/09/08 26
Components: MTS
vs. Classic
 Use classic COM for trusted, non-
transactional components
 Use COM for Session- or Application-scoped
components
 Use MTS library packages for trusted,
transactional components
 Use MTS server packages for untrusted
components, transactional or not
 Or, mark applications as isolated (OOP) and
run components inproc to the application
 Transactional components must be stateless;
other (MTS) components need not be
02/09/08 27
Component
Threading
Cause of much pain

Models
 Use Agile (Both-threaded + FTM), Apartment,
or Neutral (COM+) threading
 Never use Single or Free threading for ASP
 VB components are Apartment-threaded –- at
best; Single-threaded if not careful
 Agile => C++/ATL or Java
 Neutral => C++/ATL
 Page scope: any good model
 Session scope: Agile or Neutral preferred;
Apartment locks session down to a thread
 Application scope: Agile or Neutral only;
Apartment serializes app, requires marshalling,
runs in wrong security context
02/09/08 28
ASP Performance
(1 of 2)
 Many players & layers
 Use static HTML wherever possible: XBuilder
 Enable Response buffering
 Cache, cache, cache: Use LookupTable
 Cache object properties (inc. collections)
 Use local variables
 Use <object> instead of Server.CreateObject
 Close connections and Set to Nothing
 Don’t use Session or Application object
 Don’t store COM objects in Session or
Application state
 Disable script debugging
02/09/08 29
ASP Performance
(2 of 2)
 Avoid repeated string concatenation
 Use Response.IsClientConnected
at top of expensive pages. Only works
correctly after first Response.Write.
 Real-enough time: MSMQ
 Don’t store large arrays in
Session/Application
 Don’t redim arrays
 Copy collections to local variables
 Long, blocking pages => increase
ProcessorThreadMax
02/09/08 30
Perf: Offload work
to Clients
 CSS, DHTML
 XML
 RDS
 Remote scripting
 XmlHttp
 Client-side validation
 Minimize file sizes
 Avoid https/SSL wherever possible

02/09/08 31
Performance
Testing
 WebTool (Homer)
 PerfMon
 Tracer component
 Poor man’s ASP profiling
 Measure ASP page under high load
 Put Response.End in middle of script
 Measure page again
 If throughput and response time are about the
same, the problem’s in the first half of the script; if
they’re much improved, it’s in the second half
 Add a comment detailing the results at the
Response.End location
 Put Response.End in the appropriate half and re-
measure until problem(s) isolated

02/09/08 32
ASP Performance
Graphs ASP Performance

120

100

80

60 Uniprocessor
2P
4P

40

20

0
In-Process Out-of-Process In-Proc OOP In-Proc OOP

NT 4 Service Pack 5 NT 4 sp5, VBScript 5 Windows 2000 Beta 3

02/09/08 33
Databases (1 of 2)
 Minimize database access
 Cache transformed output
 Use ODBC connection pooling or OLEDB
resource pooling
 Use System DSNs or DSN-less DSNs, not
User DSNs or File DSNs
 Make ADO both-threaded: makefre15.bat
 Use ADO Field object
 GetString and GetRows are fast
 RDS and XML: offload work to client
 Don’t Select * -- use named columns
02/09/08 34
Databases (2 of 2)
 Use SQL Server 7.0, not Access
 Let SQL Server do the work
 stored procedures, joins, sorting, grouping
 Use Query Analyzer: Show
Execution Plan
 Use Indexes
 Named Pipes locally, Sockets remotely
 Always specify command types explicitly

02/09/08 35
New in IIS 5
 Pooled out-of-process applications
 Reliable restart
 Much improved ASP performance
 Server.Transfer preferred to Response.Redirect
 Server.Execute
 Server.GetLastError
 XML/ADO Recordsets w/ Response & Request
 Better error messages – no more ASP 0115
 Custom Errors (500-100.asp)
 Thread gating
02/09/08
 Remote scripting 36
Resources
 http://www.useit.com
 http://msdn.microsoft.com/workshop/
 http://www.15seconds.com
 http://www.activeserverpages.com
 http://www.4GuysFromRolla.com
 http://www.asptoday.com
 http://www.aspguild.org
 http://www.microsoft.com/backstage/
 http://www.aspwire.com
 http://www.htmlhelp.com
 http://www.swynk.com
 http://www.microsoft.com/technet/iis/
 Prof. ASP Techniques for Webmasters, Homer
 Information Architecture for WWW, Rosenfeld
02/09/08 37
 IIS Resource Kit

You might also like