ASP.NET Best Practices

Download Report

Transcript ASP.NET Best Practices

ASP.NET Best
Practices
Phil Wolfe, [email protected]
MCSD, MCDBA, MCT, MCP+SB
MidNET User Group President
Agenda
Best Practices for:





Upgrading
Performance
User Interaction
Maintenance
Architecture
Design






Configuration
Scalability
Security
Authentication
Authorization
Deployment
Best Practices for Upgrading

Use new built-in objects instead
of former COM components







Upload: File.PostedFile
Charts: System.Drawing
Cache/Session: Cache()
Browser Sniff: Request.Browser
Convert to ADO.NET
Separate code from content
Convert includes to controls
Best Practices for Performance






Use Caching techniques
Careful use of View State
Avoid COM Calls
Use appropriate Data Access
Others performance tips
Performance doesn’t change based
on:


Codebehind
Language
Page Output Caching






Demo
Use the @ OutputCache page
directive
Duration – length in seconds to cache
VarybyParam – use for form fields
VarybyHeader – use for HTTP headers
VarybyCustom – use your
imagination, can be browser (Major
version)
Override GetVaryByCustomString, it
returns the cache key
Fragment Caching

Use for common parts of a page





Navigation
Headers / Footers
User Controls that display the same data
initially
All controls can use attribute:
<PartialCaching()>
Uses VaryByControl
Cache API





Similar to Application object but not a
replacement
Can have key/file/time/(your own)
based dependencies
Unused items automatically expire in
5 min. (can be set relative or absolute)
Uses LRU2 algorithm when ASP.NET
worker process is low on memory
Supports Callbacks to call code on
Eviction (see help)
Use of View State
<input type="hidden"
name="__VIEWSTATE"
value="d9b...oA==" />
 Turn it off at the following levels:




Application: <pages enableViewState=“false” />
Page: <%@ Page EnableViewState=“false” %>
Control: <%@ Control EnableViewState=“false” %>
Best Practice: Turn it off by
default and turn it on per control
Avoid COM Calls

Runtime Callable Wrappers (RCW) are
just proxies to the real component



Can be done with properly designed
components such as one method call
Single-Threaded Apartment (STA)
Components (all VB6) will not work
well with ASP.NET’s MTA thread pool
Best Practice:


Migrate code to .NET (managed code)
<%@ Page ASPCompat=“true” %> = STA Page
Use appropriate data access

Use Correct Data Client



Use correct access object



SQL Client for SQL
Oracle client for Oracle
DataReader for firehose access
DataAdapter and Dataset for more
sophisticated actions
Use other design best practices


Use stored procedures
Use connection pooling via common
connection string (server;db;uid;pwd;)
Other Performance Tips






Readonly session state
Use server controls only when
needed
Early bound data types/objects
Disable tracing and debug stmts.
Use exception handling for
unknown situations not flow logic
Good hardware helps too 
Best Practices for User Interaction





Using Server controls
Implement error pages and events
Using IE specific features
Using Cookieless sessions
Smart Navigation
Server Controls

Pros



Display different for different devices
Dynamic functionality per browser
Cons



Extra CPU cycles to process them
Viewstate must be managed properly
Would be overhead for pages that don’t
require them
ex. Small search bar on every page since
it posts somewhere else.
ASP.NET Errors




Demo
Page_Error, Application_Error
<customErrors> section
Send the admin an email:
SMTPMail
Log the error EventLog
Dim Message As String = "Url " & Request.Path & _
"Error: " & Server.GetLastError.ToString
Dim Log As New EventLog()
Log.Source = “ASP_Error_Log”
Log.WriteEntry(Message, EventLogEntryType.Error)
IE Specific Features





Treeview
Buttonbar
Tabstrip
Multipage
3rd-Party

Found at:
www.123ASPX.com
www.codeproject.com
www.411asp.net
Cookieless Sessions
<sessionState cookieless=“true” />
 Munges the session id in the URL:
http://server/(lit3py55t21z5v55vlm
25s55)/vdir/SessionState.aspx
 Must use relative URLs in app
 Works on devices that don’t
support cookies
Smart Navigation





Demo
More look and feel than anything
Doesn’t cause total page flashes
Only refreshes part of page that
changes
Retains location in page (doesn’t
scroll to the top)
Supports normal Back button
functionality
Best Practices for Maintenance





User Controls
Debugging and Tracing
Web.Config
Codebehinds
Page Directives
User Controls





<%@ Control %> directive
Reusable sections of code that
encapsulate their functionality
Replace visual includes
Are fully object oriented
Dynamically load


Include @Register
Make them strongly typed
ctype(loadcontrol(“path”), mycontrol)
Debugging & Tracing

Keep debug and trace statements
in code for later reuse



Debug can be left in
Set trace=“false” when done
Use Trace.axd

Is handled in machine.config and
enabled in the web.config

<trace enabled=“true” requestLimit=“10” />

Components can write to the trace file
using httpcontext.current.trace.write
Web.Config

XML configuration file



Many different settings can be set



1 per directory
Settings are inherited and unioned
Doesn’t require a recompile unlike the
global.asax
See help for available settings
Can be edited on the fly from
anywhere
Codebehinds



Demo
New way of separating code from
content
Content inherits from a page
class
All code belongs in the
codebehind


Some databinding exceptions
No inline exceptions!!!
Ex. <title><%= strTitle%></title>
Becomes <title id=“lblTitle” runat=“server”></title>
Page Directives







Buffer = “true”
EnableSessionState = “true”
EnableViewState = “true”
Explicit = “false”
Strict = “false”
Trace = “false”
These are the defaults (consider
reversing)
Best Practices for
Architecture Design





Use 3-Tier design
Components should run in the
same process as the Web App
Call business logic directly
Plan for Web Farms
Application Variables vs. Statics
3-Tier Design

By separating applications into 3
logical components the
application becomes modularized



User – ASP.NET pages & code for
devices. Code specific for display
Business – .VB/.CS components. Code
that is specific to your business.
Data – SQL/Oracle/XML/WS. Black box
that your code makes calls to.
Inprocess Components



Your code should not alter its
identity or security.
This requires that the calling
application have rights to perform
the action.
– OR –
Component Services will
impersonate the appropriate user.
Good Business Logic Use

Do not call YOUR Web Services
from YOUR Web Application.
– Call the Business Logic Directly
Web Service
ASPX
Business
Logic
DB
Web Farms


If your design begins with the
assumption that browsers won’t
always return to the same
machine your application will
immediately be able to move to
more than one box.
Session State can be held in:


Stateserver Service
SQL Server
Application Variables



ASP.NET worker process can
cycle when they want
Application variables will be reset
to their defaults when this
happens
Consider defining static variables
if you know this variable does not
change in your application
Best Practices for Configuration





Use Web.config  see
Maintenance
Use <appSettings> for
configurable data
Custom configuration handlers
Location allowOverride = false
Encrypt passwords and only let
Admin have permissions to the
file
appSettings section
<appSettings>
<add key=“…” value=“…” />
</appSettings>
…
Configuration.AppSettings(“key”, string)


Allows you to store key/value
pairs that are not compiled into
your code
Can be easily changed
Custom Configuration Handler




If you want your own web.config
section apart from appSettings
Implement
iConfigurationSectionHandler
Register in <configSection>
See Help
Location attribute
To apply settings to a specific
section of your application.
<configuration>
<location path=“myvdir”>
<system.web>
…Specific config…
</system.web>
</location
</configuration>

Protect passwords


With forms auth you can store
passwords in web.config
Store them with encryption so
they can’t be stolen
Best Practices for Scalability




Session state considerations
Web services
Components
Connection pooling in ASP.NET
Session State


Use out-of-process session state
to support multiple machines
Start Service


net start aspnet_state
Enable in web.config
<sessionState mode=“StateServer”
stateConnectionString=“tcpip=ip:port” />

Supports cycling of the ASP.NET
worker process
Web Services




Can distribute parts of the
application on other machines
Web service could be a different
technology or platform
Will be able to service more
clients but may not be as
responsive
Components may be a faster
implementation
Components


Components can exist on other
machines running in Component
Services
Use .NET Remoting to access
them
Connection Pooling



.NET managed provider for SQL
server automatically does
connection pooling
You must use the same
connection string!
Use the following performance
counter:

SQLClient : Current # pooled
connections
Best Practices for Security



IIS gets request first so pass it to
ASP.NET
Impersonate
Implement custom HTTPModules
IIS Security


IIS has a chance to handle
security but is managed in the
metabase
Let IIS pass the user on to
ASP.NET and it can determine the
authentication method
Impersonation
ASP.NET can now impersonate
users
 Impersonation is off by default
 If the process (thread) doesn’t
need to have the security context
of different users, then don’t
impersonate them
<identity impersonate="true"
userName="contoso\Jane"
password="pass" />

Custom HTTPModules




Demo
Components that can handle any
of ASP.NET’s events
Implement the IHTTPModule
interface
Register in the web.config
Relates to security in that the
developer can track subscribers
and charge per usage or roll your
own authentication scheme
Best Practices for Authentication



Windows Authentication
Forms Authentication
Custom Authentication
Windows Authentication


Best Practice for Intranets
Pros


Seamless login for windows users
Cons



Can’t login as someone else
Can’t customize popup box
User must exist in Active Directory
Demo
Forms Authentication


Best Practice for Internet
Pros





Can customize login screen
Can encrypt the data with SSL
Flexible credential store
Works in all browsers
Cons




Not as secure
Uses cookies that can be hijacked
User doesn’t have a Windows Principal
More Code??
Demo
Custom Authentication


Even more customizable
Pros




Even more customizable
Accomplished by custom HTTPModule
or Sub Application_AuthenticateRequest
Use for custom SOAP auth or mobile
devices
Cons

Even more code + understanding
Best Practices for Authorization

Use URL Auth




Controlled with allow or deny tags (don’t
have to be on the server to configure)
Can apply to non-windows accounts
(unlike ACLs)
Deployment is eased because
permissions don’t need to be reset
Custom

Using HTTPModule or
Application_AuthorizeRequest
Best Practices for Deployment




Performance counters
Stress testing with Application
Center Test
Correct encryption keys in
web.config
Set Process model recovery
Performance Counters
Imports System.Diagnostics
Sub Some_Event()
Dim myCounter as PerformanceCounter
myCounter = new PerformanceCounter( _
“Portal”, “Logged_On”, “Intranet”, _
False)
myCounter.incrementBy(1)
myCounter = nothing
End Sub
Demo
Stress Testing






Application Center Test is now
included with VS.NET
Explore pre-built samples
Record your own stress script
Combine the knowledge of both so
make a good test script
Know the performance numbers you
want to hit
Stress a box better than your web
server. Numbers scale down, not up!
Web.config Encryption Keys

Confirm that all servers have the
same keys
Process Model element


In Machine.config
<processModel
requestLimit - # of requests
before a new process
timeout - # of minutes before a
new process
maxWorkerThreads - # of threads
per processor
References




MSDN Web Site
Visual Studio.NET Documentation
TechEd 2001 Presentations
Wrox Professional ASP.NET
Questions
Phil Wolfe
[email protected]