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
         
02/09/08

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
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)
4

02/09/08

ASP Lessons Learned
 

Use script as glue only Developing Applications

Develop applications, not just stand alone pages Cache Inputs Cache Outputs Threads per processor Set absolute goals, not just relative goals
5

Caching
 

Blocking versus Non-blocking scripts

Benchmark

02/09/08

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)
6

02/09/08

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


02/09/08

Jakob Nielsen, www.useit.com
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

  
02/09/08

Non-browser user agents: spiders Frames Cookies for personalization
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
9

02/09/08

3- or 4-Tier Design
Middle Tier -- ASP

Client Tier Browsers

Presentation Layer ASP

Business Logic Components

Data Tier DBMS

02/09/08

10

Readability and Maintainability
  

 


02/09/08

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
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
15

02/09/08

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) convenient but problematic Seductively
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
19

  

  
02/09/08

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)

  
02/09/08

Querystring parameters Munged URLs (like Amazon) Hidden FORM variables

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”

 
02/09/08

Server caching Proxy caching Client caching

23

Components (1 of 3)

Performance

Excessive script

 

    
02/09/08

Scalability Isolate Business Logic from ASP Presentation Layer Reuse by ASP and other environments Transactions Strong Typing Access OS features Protect Intellectual Property
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
25

02/09/08

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
26

02/09/08

Components: MTS vs. Classic
 

Use classic COM for trusted, nontransactional 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
27

02/09/08

Component Threading Models Cause of much pain
   

   

02/09/08

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

28

ASP Performance (1 of 2)
         


02/09/08

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

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
30

02/09/08

Perf: Offload work to Clients
       

CSS, DHTML XML RDS Remote scripting XmlHttp Client-side validation Minimize file sizes Avoid https/SSL wherever possible
31

02/09/08

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 remeasure until problem(s) isolated
32

02/09/08

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)
  

    
02/09/08

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
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
35

02/09/08

New in IIS 5
         
02/09/08

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 36

Resources
             
02/09/08

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 37 IIS Resource Kit