asp best practices
TRANSCRIPT
04/07/23 1
ASP Best Practices
George V. Reilly
Software Design Engineer
Internet Information Services
Microsoft Corporation
04/07/23 2
ASP Best Practices How to build good Active Server Pages
applications, with an eye to robustness, correctness, maintainability, and performance.
What not to do.
04/07/23 3
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
04/07/23 4
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)
04/07/23 5
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
04/07/23 6
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)
04/07/23 7
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
04/07/23 8
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
04/07/23 9
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
04/07/23 10
3- or 4-Tier Design
ClientTier
Browsers
PresentationLayer
ASP
BusinessLogic
Components
DataTier
DBMS
Middle Tier -- ASP
04/07/23 11
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
04/07/23 13
Internationalization/Localization 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
04/07/23 14
Miscellaneous Use fine-grained #includes to factor
and reuse code Break queries into Page i of N.
04/07/23 15
Testing Proofread the content Multiple Browsers Stress Testing Performance Testing Homer, er, Web Application Stress Tool IIS Exception Monitor WebMeter Mutek BugTrapper
04/07/23 17
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
04/07/23 19
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
04/07/23 20
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
04/07/23 21
Application State Useful for shared data Non-persistent Doesn’t work well in webfarms => only
readonly state useful
04/07/23 22
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
04/07/23 23
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 Client caching
04/07/23 24
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
04/07/23 25
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
04/07/23 26
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
04/07/23 27
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
04/07/23 28
Component Threading Models Cause of much pain 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
04/07/23 29
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
04/07/23 30
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
04/07/23 31
Perf: Offload work to Clients CSS, DHTML XML RDS Remote scripting XmlHttp Client-side validation Minimize file sizes Avoid https/SSL wherever possible
04/07/23 32
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
04/07/23 33
ASP Performance Graphs
0
20
40
60
80
100
120
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
ASP Performance
Uniprocessor
2P
4P
04/07/23 34
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
04/07/23 35
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
04/07/23 36
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 Remote scripting
04/07/23 37
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 IIS Resource Kit