Title: DEVT1-56: ASP.NET Best Practices
1Best Practices for ASP.NET Development
Joe Healy Microsoft Corporation
2What we will cover
- Designing ASP.NET Web forms
- Use code-behind for best performance and
scalability - ASP.NET caching techniques
- State management options
- Recommendations for communicating with COM
components from ASP.NET
3Session Prerequisites
- Understand .NET architecture
- Working knowledge of either VB.NET or C
- Knowledge of ASP.NET application architecture
- Knowledge of ASP
Level 300
4Agenda
- Language and Code Practices
- Server Control Design Practices
- Component and User Control Usage Practices
- State Management Recommendations
- Caching Techniques
- Deployment Best Practices
- Measurement Techniques
5Language and Code PracticesCode Performance
- .NET Common Language Runtime (CLR) provides big
runtime performance wins - No perf difference in .NET languages
- Equivalent code written in VB and C provides
equivalent performance at runtime
6Language and Code PracticesBinding in VB.NET
- Early binding in VB performs better than late
binding
VB Late Binding Example Dim j, obj obj New
System.Collections.ArrayList() for j 0 To i
obj.Add(j) Next VB Early Binding Example Dim
j as integer, obj As ArrayList obj New
System.Collections.ArrayList() for j 0 To i
obj.Add(j) Next
7Language and Code PracticesLanguage
Recommendations
- Avoid using late binding in VB and JScript
- Explicitly declare all variable types (Dim a as
Long) - Avoid late bound methods on Object type
- Use lt_at_ Page LanguageVB Explicittrue gt
- Requires all variables to be declared (DIM
required) - Still enables late bound code to exist though
- lt_at_ Page LanguageVB Stricttrue gt
- Disallows any late bound code to be used
8Language and Code PracticesCOM interop Issues
- Transitions between managed and unmanaged
code can be expensive - With methods having complicated structures as
arguments and return types - Use chunky over chatty APIs
- Apartment threaded components are must b e
handled appropriately in ASP.NET - ASP.NET now uses MTA thread pool by default. If
not deal with MTA pool has very bad perf side
effects when running STA components - This affects all VB6( STA) components!
9Language and Code Practicesinterop
Recommendations
- Ideally migrate COM code to .NET
- Alternatively structure APIs to be less chatty
and more chunky in usage - Use COM interop through System.Runtime.interopServ
ices - If using apartment components, mark page to run
in STA compat mode - lt_at_ Page ASPCompattrue gt
- Generate early bound .NET wrappers for COM
components (using TLBIMP.exe) - Note this does not remove aspcompattrue
requirement for apartment components
10Language and Code Practicesinterop
Recommendations
- Be careful not to declare any STA component in
constructor of page
bad!!!! Public Sub New() mathtest New
STATest.MathClass() End Sub good!!! Private
Sub Page_Load() Handles MyBase.Load mathtest
New STATest.MathClass() End Sub
11Demonstration 1Language Best Practices Early
binding vs. Late Binding Using COM objects in
ASP.NET
12Agenda
- Language and Code Practices
- Server Control Design Practices
- Component and User Control Usage Practices
- State Management Recommendations
- Caching Techniques
- Deployment Best Practices
- Measurement Techniques
13Server Control Design PracticesOptimizing Server
Control Rendering
- Server controls provide a very clean programming
model abstraction - Recommended way to build ASP.NET pages
- Server controls do more rendering/postback work
that old-style lt gt code - Should understand what this work is and optimize
for it accordingly - Two areas to think about and optimize
- Rendering Content
- ViewState Postback
14Server Control Design PracticesOptimizing Server
Control Rendering
- Server controls encapsulate rendering markup
logic at runtime - Handle style and automatic uplevel/downlevel
functionality management - individual server controls each add slight
additional rendering cost - Additional allocations for style management
- Additional allocations for control itself
- Net take the more individual server controls on
page, the more this overhead can be noticed - Need to be especially aware of this w/ composite
list controls that generate multiple controls per
data row
15Server Control Design PracticesOptimizing Use of
Viewstate
- ASP.NET allows pages/controls to maintain state
across round trips by storing state within hidden
viewstate field - Disabled with EnableViewState attribute
- Some downsides
- increases network payload
- Performance overhead to serialize this
- Recommendation
- Always review your usage of this feature
- Always disable if you are not doing postback
- Disable on per control basis if possible
- Use lt_at_ Page Tracetrue gt to track usage size
16Server Control Design PracticesData Validation
Techniques
- Leverage client side scripting capabilities to
perform validations - Perform validation on both server client side
to avoid validation bypass - Make appropriate use of the RequiredFieldValidator
- Use RegularExpressionValidator for validating
complex field types like Credit Card
17Demonstration 2Server Control Design Practices
Optimizing Server Control RenderingOptimizing
Use of ViewstateData Validation Best Practices
18Agenda
- Language and Code Practices
- Server Control Design Practices
- Component and User Control Usage Practices
- State Management Recommendations
- Caching Techniques
- Deployment Best Practices
- Measurement Techniques
19Component User Control PracticesImproving User
Experience
- ASP.NET built-in caching features
- Output Caching
- Fragment Caching
- Caches the static result of an ASP.NET page
- Use the lt_at_ OutputCache gt directive to control
caching behavior
20Component User Control PracticesImproving User
Experience
- Caching Options
- Duration - Time item exists in the cache
- VaryByParam - Varies cache entries by Get/Post
params. Name param, separate by semi-colons,
supports - VaryByHeader - Varies cache entries by Http
header - VaryByCustom - Override method within Global.asax
to custom vary by whatever you want (you control
the cache key)
21Component User Control PracticesImproving User
Experience
- Caching the entire page isnt always possible
- Partial page personalization, etc.
- Fragment Caching allows caching regions of a page
by using user controls (.ascx) - User controls define lt_at_ OutputCache gt directive
22Component User Control PracticesOptimizing
Data Flow Across Tiers
- Minimize the number of post backs
- Leverage client side capabilities to avoid post
backs - Control the amount of view state information
passed during a post back - Use EnableViewState at page or control level to
configure view state usage.
23Demonstration 3Component User Control Best
Practices Buffered OutputFragment Caching
Code Behind, User Controls Components
24Agenda
- Language and Code Practices
- Server Control Design Practices
- Component and User Control Usage Practices
- State Management Recommendations
- Caching Techniques
- Deployment Best Practices
- Measurement Techniques
25State Management Recommendationsin Proc Session
State
- Session state is stored in the ASP.NET worker
process - Recycling the process will cause all session
state to be lost - Session state performance is maximum in this mode
26State Management RecommendationsOut of Proc
Session State
- Session state can be stored in a State server
process running on the same machine or a
different machine - State can also be stored in a SQL Server database
- Restarting the web server does not cause the
session state to be lost - More reliable than in process session state but
less performant
27State Management RecommendationsConfiguring
Session State
- Session state can be configured via the
ltsessionStategt element in the web.config file - Change causes ASP.NET application to be
restarted, all new sessions will be stored as per
the updated session configuration - Out of process session state stores like State
Server or SQL Server must be started configured
properly
28Demonstration 4State Management Best Practices
State ManagementSession State in A State Server
29Agenda
- Language and Code Practices
- Server Control Design Practices
- Component and User Control Usage Practices
- State Management Recommendations
- Caching Techniques
- Deployment Best Practices
- Measurement Techniques
30Caching TechniquesDesign for Caching
- Leverage the built-in ASP.NET built-in caching
features - Output Caching
- Fragment Caching
- Cache API
- Recommendation
- Specifically design your pages around these
features can lead to massive perf wins
31Caching TechniquesOutput Caching
- Caches the static result of an ASP.NET page
- Declarative lt_at_ OutputCache gt directive
- Optional Output Cache APIs can also be called
- Caching Options
- Duration
- Time item exists in the cache
- VaryByParam
- Varies cache entries by Get/Post params
- Name param, separate by semi-colons, supports
- VaryByHeader
- Varies cache entries by Http header
- VaryByCustom
- Override method within Global.asax to custom vary
by whatever you want (you control the cache key)
32Caching TechniquesFragment Caching
- Caching the entire page isnt always possible
- Partial page personalization, etc.
- Fragment Caching allows caching regions of a page
by using user controls (.ascx) - User controls define lt_at_ OutputCache gt directive
- Additional Features
- VaryByControl Varies cached items by controls
- VaryByCustom Allows user cache key method
33Caching TechniquesCache API
- Caching output isnt always possible
- Cache API allows objects to be cached
- in memory Hashtable
- System.Web.Caching.Cache class
- Page intrinsic property (Cache)
- Features
- Dependencies (key, file, time)
- Unused items automatically expire
- Supports Callbacks
34Demonstration 5Caching Techniques Output
CachingCustom Caching
35Agenda
- Language and Code Practices
- Server Control Design Practices
- Component and User Control Usage Practices
- State Management Recommendations
- Caching Techniques
- Deployment Best Practices
- Measurement Techniques
36Deployment Best PracticesLogical Design
- Design your applications using logical 3-Tier
Design Practices - Pages (.aspx) and User Controls (.ascx)
- Reusable Biz Classes in \bin dir (.vb .cs)
- Data within a SQL Database
- Design your Web application so that it can be
distributed across a Web farm - Your code shouldnt assume that a client will
always return to the same machine - Be careful of assumptions regarding statics and
application state
37Deployment Best PracticesPhysical Deployment
- Deploy your applications such that the pages and
components run in same process - Deploying onto remote servers connected via DCOM
or Web Services will almost always hurt your
performance/scalability - Leverage Web services only for application to
application communication -- not intra app calls - Leverage ISA Server for configurations where a
DMZ security zone is required - Enables you to restrict app server access from
browser clients
38Deployment Best PracticesISA for DMZ
Configurations
39Agenda
- Language and Code Practices
- Server Control Design Practices
- Component and User Control Usage Practices
- State Management Recommendations
- Caching Techniques
- Deployment Best Practices
- Measurement Techniques
40Measurement TechniquesOverview of Application
Center Test
- Application Center Test (ACT) is a tool designed
for stress testing web servers - The tool assists in determining performance and
scalability of a given web site - The tool also collect useful statistical
information during the stress test - ACT also exposes a programming interface, which
can be used for creating stress test scripts
41Measurement TechniquesKey Performance indicators
- The key performance indicators of a web
application are - Processor utilization
- Low value indicates blocking on other resources
- ASP.NET
- Requests/Sec Requests Queued
- Memory
- Pages Faults/Sec lower the better, high numbers
indicate insufficient memory condition
42Measurement TechniquesStress Testing
- Stress testing is a defensive mechanism to
creating scalable web sites - Stress runs will indicate the scalability of the
application - Can be used to determine scale of operation, when
to add new hardware etc - Stress testing should not be the final step in
building a web application. It should be
integrated into the development life cycle - Narrow the scope of a stress run to get more
accurate, actionable results
43Measurement TechniquesStress Testing
- Use the web site logs to determine operational
load - Stress tools like WAS (Homer) allow log files
to be replayed on a web site and record
statistical performance information - Run performance monitoring tools on the live
servers to identify scalability issues
44Measurement TechniquesDesigning Scalable
Applications
- Two ways to quantify Web performance
- Machine Throughput (requests/sec)
- Response Time (time to first/last bytes)
- Measure performance by stressing server
- Utilize multiple client stress machines
- Use Application Center Test tool
- Measure multiple scenarios
- Simulate end to end scenario walkthroughs of site
- Measure individual page performances
45Measurement TechniquesDesigning Scalable
Applications
- Quantify performance for a range of load
conditions - Request/sec using different loads (100, 250, 500,
750, 1000, etc concurrent clients) - Identify maximum client load that fits into
acceptable TTFB/TTLB response time range - Use ASP.NET Caching to cache page output
- Design pages to maximize use of cache
46Demonstration 6Measurement TechniquesPerformanc
e Measurement
47Session Summary
- in this session we discussed
- Language and Code Practices
- Server Control Design Practices
- Component and User Control Usage Practices
- State Management Recommendations
- Caching Techniques
- Deployment Best Practices
- Measurement Techniques
48Thank You To Our Sponsors!
49Thank You To Our Sponsors!
50How-To ResourcesSimple, Step-By-Step Procedures
- Embedded Development How-To Resources
- General How-To Resources
- integration How-To Resources
- JScript .NET How-To Resources
- .NET Development How-To Resources
- office Development Resources
- Security How-To Resources
- Visual Basic .NET How-To Resources
- Visual C .NET How-To Resources
- Visual Studio .NET How-To Resources
- Web Development How-To Resources (ASP, IIS, XML)
- Web Services How-To Resources
- Windows Development How-To Resources
- http//msdn.microsoft.com/howto
51MSDN Webcastsinteractive, Live Online Event
- interactive, Synchronous, Live Online Event
- Discuss the Hottest Topics from Microsoft
- Open and Free for The General Public
- Takes Place Every Tuesdays
- http//www.microsoft.com/usa/webcasts
52MSDN Subscriptions THE way to get Visual Studio
.NET
MSDN Subscriptions
Visual Studio .NET
- Enterprise Architect
- Software and data modeling
- Enterprise templates
- Architectural guidance
MSDN Universal2799 new2299 renewal/upgrade
- Enterprise Developer
- Enterprise lifecycle tools
- Team development support
- Core .NET Enterprise Servers
MSDN Enterprise2199 new1599 renewal/upgrade
NEW
- Professional
- Tools to build applications and XML Web services
for Windows and the Web
MSDN Professional1199 new899 renewal/upgrade
53Where Can I Get MSDN?
- Visit MSDN Online atmsdn.microsoft.com
- Register for the MSDN Flash Email Newsletter at
- msdn.microsoft.com/flash
- Become an MSDN CD Subscriber at
msdn.microsoft.com/subscriptions - MSDN online seminars
- msdn.microsoft.com/training/seminars
- Attend More MSDN Events
54MS PressEssential Resources for Developers
Microsoft Visual Studio .NET is here! This is
your chance to start building the next big thing.
Develop your .NET skills, increase your
productivity with .NET Books from Microsoft
Press www.microsoft.com/mspress
55TrainingTraining Resources for Developers
- Course Title introduction to Microsoft ASP.NET
- Course Number2063
- Availability Now
- Detailed Syllabus www.microsoft.com/traincert
-
To locate a training provider for this course,
please access www.microsoft.com/traincert
Microsoft Certified Technical Education Centers
are Microsofts premier partners for training
services
56New Application Developer Certification
- What is MCAD?
- Microsoft Certified Application Developer
- A certification for developers who use Microsoft
tools and technologies to develop and maintain
department-level applications, components, Web or
desktop clients, or back-end data services. - How do I attain the MCAD certification?
- 2 core exams
- 1 elective exam
- For complete information visit
www.microsoft.com/mcad
57Become A Microsoft Certified Solution Developer
- What is MCSD?
- Microsoft Certified Solution Developer
- The premier certification for lead developers who
design and develop leading-edge enterprise
solutions with Microsoft development tools,
technologies, and the Microsoft .NET Framework. - How do I attain the MCSD for Microsoft .NET
certification? - 4 core exams
- 1 elective exam
- For complete information visit
www.microsoft.com/mcsd
58(No Transcript)