DEV310 Top 10 Tricks for a “Killer” Web Application
Download
Report
Transcript DEV310 Top 10 Tricks for a “Killer” Web Application
DEV310
Top 10 Tricks for a
“Killer” Web Application
Paul D. Sheriff
PDSA, Inc.
[email protected]
Ken Getz
MCW Technologies, LLC
[email protected]
Demos available for download in VB.NET and C# at:
http://www.mcwtech.com/2004/teched/us
Us.About
Paul D. Sheriff
President of PDSA, Inc.
www.pdsa.com
Ken Getz
KNG Consulting, Inc.
www.mcwtech.com,
www.developershandbook.com
Microsoft Regional Directors,
SoCal
Addison-Wesley Book
ASP.NET Developer’s Jumpstart
Assumptions
You are familiar with:
Programming in .NET
ASP.NET
ADO.NET
N-Tier concepts
The demos are in VB.NET
All concepts apply to C# as well
Case Study
Transamerica
Developed during .NET Beta 2 / .NET 1.0
PDSA, Inc. helped them architect
application for re-use
Created standards for development
These tips and tricks are from that project
http://www.microsoft.com/casestudies
Best Practices For Best Web Sites
How do I…
Create an n-tier design for my Web site?
Store and retrieve application settings?
Create a dynamic and flexible
user interface?
Ensure common code runs each time a
page is loaded?
Track users’ actions throughout my
Web application?
Best Practices For Best Web Sites
How do I…
Track and notify tech support of
exceptions that occur?
Provide bullet-proof access to
Session variables?
Ensure unexpected errors are handled
gracefully?
Assign roles to users and secure
Web pages?
Provide the best performance?
Disclaimer
The code in this session is…
For demonstration and for teaching
techniques
NOT production code
Demo
Investigate the sample
How Do I Create An
N-Tier Design?
Create N-Tier Design
Create your own data layer
(Class Library) project
Encapsulate all SQL in classes
Return DataSets and DataReaders
Typed DataSets
Your own object that implements
IListSource or other bindable interface
Create N-Tier Design
Three Projects
User Interface
Business/Data Layer
Common Classes
eNorthwind
UI
NorthwindDataLayer
Business/Data Layer
WebCommon
Common Web Classes
Create N-Tier Design
Data Layer
Base Class
Contains ADO.NET code
Business/Data Classes
SQL and Business rules
CategoriesDC ProductsDC OrdersDC
SqlHelper
ADO.NET Code
Create N-Tier Design
For example, loading a DropDownList
Private Sub LoadCategories()
Dim dc As CategoriesDC, dr As IDataReader
dc = New _
CategoriesDC(WebAppConfig.ConnectString)
dr = dc.GetCategories()
ddlCategories.DataTextField = "CategoryName"
ddlCategories.DataValueField = "CategoryID"
ddlCategories.DataSource = dr
ddlCategories.DataBind()
dr.Close()
End Sub
Create N-Tier Design
Why is this important?
Allows you to reuse data layer in desktop
applications, mobile Web apps, and more
Gives you flexibility to change data
access method late in the
development process
Create N-Tier Design
Why is this important?
Centralizes SQL
No dependence on connections in UI layer
Allows you to modify and tune SQL in
one place
Can switch from SQL statements to stored
procedures
Create N-Tier Design
Demo 1 of 9
Things to look at
HomePage.aspx code that calls the data
layer
LoadCategories method
CategoriesDC and SqlHelper classes
How Do I Work With
Application Settings?
Work With Application Settings
Use ConfigurationSettings.AppSettings
to get values from default
<appSettings> section
Most people use this technique:
ConfigurationSettings. _
AppSettings("ConnectString")
Can be slow
Reads Web.Config file each time
Reads one item at a time
Work With Application Settings
Create your own class that supplies
application settings
Use shared/static methods to
expose data
Where might you store settings?
Web.Config
XML file
Registry
Database table
Work With Application Settings
Private Sub LoadCategories()
Dim dc As CategoriesDC, dr As IDataReader
dc = New _
CategoriesDC(WebAppConfig.ConnectString)
dr = dc.GetCategories()
ddlCategories.DataTextField = "CategoryName"
ddlCategories.DataValueField = "CategoryID"
ddlCategories.DataSource = dr
ddlCategories.DataBind()
dr.Close()
End Sub
Work With Application Settings
Can create your own configuration
section handler
Implement IConfigurationSectionHandler
See WebAppConfig
IConfigurationSection
WebAppConfig.ConnectString
<configSections>
<section name="AppConfig"
type="WebCommon.WebAppConfigHandler,
WebCommon" />
</configSections>
<AppConfig>
Class WebAppConfig
<add key="ConnectString" value="..." />
Shared Sub New()
</AppConfig>
ConfigurationSettings. _
GetConfig("AppConfig")
Function Create
End Sub
mConnect =
nvc("ConnectString")
Shared Property ConnectString
End Sub
Return mConnect
End Property
Work With Application Settings
Why is this important?
Flexibility to change data storage location
No need to rewrite all your code if
location changes
Just rewrite the configuration class
Work With Application Settings
Demo 2 of 9
Things to look at
Web.Config file
WebAppConfig class
How Do I Create A
Dynamic And Flexible
User Interface?
Maintainable User Interface
User controls: best for applicationspecific user interface
Server controls: best for
multi-application solutions
Style sheets: for consistent UI
Maintainable User Interface
User Controls
Headers
Navigation
Data-driven menu system
Repeated groups of controls
Name, City, State, Postal Code
Phone number and extension
Maintainable User Interface
Server Controls
Design your own controls
Inherit from existing
Extend with more functionality
Maintainable User Interface
Style Sheets
Apply a style sheet to all pages
Makes global changes much easier
Frameless design
Can use <Div> tags
Use style sheet for absolute positioning
Maintainable User Interface
Demo 3 of 9
Things to look at
User Controls
Header
Data Driven Menu System
Style sheet
<div> tag
How Do I Ensure
Common Code Runs
Each Time A Page
Is Loaded?
Create A Base Page Class
Inherit from built-in Page class
Override OnLoad
Override OnError
Add custom methods
Exception Publishing
User Tracking
More, as necessary
Create A Base Page Class
Public Class WebPageBase
Inherits System.Web.UI.Page
...
Protected Overrides Sub OnLoad( _
ByVal e As System.EventArgs)
MyBase.OnLoad(e)
If Not Page.IsPostBack Then
If mTrackUser Then
HandleUserTracking()
End If
End If
End Sub
...
End Class
Create A Base Page Class
Why is this important?
Ensure important code runs on each page
Track users
Publish unexpected errors
Allows for flexibility in the future
Create A Base Page Class
Demo 4 of 9
Things to look at
HomePage.aspx (Inherits statement)
WebPageBase class
How Do I Track Users’
Actions Throughout My
Web Application?
Track Users’ Actions
Override OnLoad in base page class
Create a table in your database
Track statistics
User Name
Page Name
Site Name
Date/Time
Track Users’ Actions
Why is this important?
Statistics on page visits
Who went to which page and when
Can use your database to track usage
Can provide a web interface to statistics
Can add additional info you wish to track
Order number
User Profile Info
Track Users’ Actions
Demo 5 of 9
Things to look at
WebPageBase.HandleUserTracking
How Do I Track And
Notify Tech Support Of
Exceptions That Occur?
Track Exceptions
Microsoft Exception Management
Block
Consistent approach to exception
management
Add additional exception publishers
Turn publishers on and off dynamically
Download from Microsoft’s site
One of several application blocks
Two assemblies are needed with
your application
Track Exceptions
Steps to follow
1. Create your own exception publishers
2. Add support for publisher in Web.Config
3. Publish the exception using the Microsoft
Exception Management Block
Track Exceptions
How do you do it?
Create class that implements
IExceptionPublisher
Implement Publish method
Write information to event log, database
or e-mail
Add necessary configuration information
to Web.Config
Within Catch block call Publish method
Track Exceptions
Private Sub LoadCategories()
Dim dc As CategoriesDC
Try
dc = New _
CategoriesDC(WebAppConfig.ConnectString)
' code omitted
Catch ex As Exception
WebException.Publish(ex)
End Try
End Sub
Track Exceptions
Why is this important?
Can track all errors that have occurred
on the site
Can receive email notification of errors
Can add publishers at runtime
Can receive additional information
about error
Stack trace
User Name, Page Name
Other application variables
Track Exceptions
Demo 6 of 9
Things to look at
Web.Config
WebException.Publish method
WebCommon.EmSql and
EmEmail classes
How Do I Provide
Bullet-Proof Access To
Session Variables?
Work With Session Variables
Normally, refer to session variables
using string index into a collection:
txtCust.Text = Session("CustID").ToString()
Type the name wrong?
You get the wrong info
Values are loosely typed
Always returns Object
Work With Session Variables
To solve the problem
Create class that “wraps up” access to
Session variables
Use Shared/static members to work with
Session
Work With Session Variables
Why is this important?
Reduces runtime errors
Allows IntelliSense while coding
Avoids type-casting issues
Work With Session Variables
Demo 7 of 9
Things to look at
CustomersMain.aspx
WebSessionInfo class
How Do I Ensure
Unexpected Errors Are
Handled Gracefully?
Handle Unhandled Exceptions
Override OnError method in base
page class
Use <customErrors> element in
Web.Config
Handle Unhandled Exceptions
Why is this important?
Provides design pattern for
unhandled errors
Allows you to publish unhandled errors
Ensures users do not see the default
ASP.NET error page
Handle Unhandled Exceptions
Demo 8 of 9
Things to look at
OnError event in WebPageBase
<customErrors> in Web.Config
How Do I Assign Roles
To Users And Secure Web
Pages?
Manage Security And Roles
Use Windows or Forms-based security
Forms-based authentication
Best for Internet sites
ASP.NET makes this very easy
Windows-based authentication
Best for Intranet/Extranet sites
Manage Security And Roles
Modify Authentication and
Authorization sections in Web.Config
<authentication mode="Forms">
<forms name="eNorthwindCookieName"
loginUrl="Admin/Login.aspx" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
Setting Security Cookie
If LoginValid() Then
FormsAuthentication. _
RedirectFromLoginPage(txtLogin.Text, False)
Else
lblMessage.Text = "Invalid LoginID"
End If
Manage Security And Roles
Why is this important?
Secure a certain portion of your web site
Grant users within roles access to
secured portions of your web site
Manage Security And Roles
Demo 9 of 9
Things to look at
Web.Config
<Authentication>
<Authorization>
<Location>
Login.aspx
CustomersMain.aspx
IsInRole
Global.asax
Application_AuthenticateRequest
Summary
OOP techniques are key to flexibility
User controls and style sheets can
make your web site much easier to
customize
Create design pattern for error
handling
Security important in every application
Compile your own tips
Keep them somewhere you can find them
Review regularly
Thanks for Coming!
Paul D. Sheriff
[email protected]
Ken Getz
[email protected]
Demos available at:
http://www.mcwtech.com/2004/teched/us
Appendix
How Do I Provide The
Best Performance?
Improve Performance
Performance is a full session’s worth
of information!
Many ways to optimize
ADO.NET
Caching techniques
Optimization must be something you
think about all the way through your
development cycle
Improve Performance
ADO.NET Tips
Use native providers, if possible
Use SqlClient instead of OleDb
Use a DataReader for loading
drop-down lists
Cache frequently used data
Read data from a database and store in XML
file on local file system
Use stored procedures
Improve Performance
Cache User Controls if possible
Cache Pages that don’t change often
Store ViewState on the server
MSDN Magazine (Dino Esposito’s article
Feb 2003)
http://msdn.microsoft.com/msdnmag/
issues/03/02/CuttingEdge/default.aspx
Improve Performance
Use HTML controls instead of server
controls for best performance
Use client-side scripting for validation
Avoids post back
Compile as "Release" before deploying
to production
Improve Performance
Don’t use Response.Redirect within
Try/Catch block
Can cause ThreadAbortException
Exceptions are expensive
Move outside the Try/Catch block
Improve Performance
Use a custom class for reading values
from Web.Config
Much faster than using AppSettings
Reading from Registry is very slow!
If you store config settings here, make
sure you cache them after reading
Much slower than AppSettings
Improve Performance
Disable SessionState when not
needed
By default, it’s always on
Disable ViewState when not needed
By default, it’s always on
Can disable on a control or page level
Use in-process session state
if possible
If you are not using a web farm
If you don't need redundancy/fail over
Improve Performance
Make sure you are checking
Page.IsPostback
Avoid running code each time back to
a page
Use buffered string access
StringWriter or StringBuilder
Avoid making calls to
COM components
Rewrite using managed code, if possible
Attend a free chat or web cast
http://www.microsoft.com/communities/chats/default.mspx
http://www.microsoft.com/usa/webcasts/default.asp
List of newsgroups
http://communities2.microsoft.com/
communities/newsgroups/en-us/default.aspx
MS Community Sites
http://www.microsoft.com/communities/default.mspx
Locate Local User Groups
http://www.microsoft.com/communities/usergroups/default.mspx
Community sites
http://www.microsoft.com/communities/related/default.mspx
Please fill out a session evaluation on CommNet
Q1: Overall satisfaction with the session
Q2: Usefulness of the information
Q3: Presenter’s knowledge of the subject
Q4: Presenter’s presentation skills
Q5: Effectiveness of the presentation
© 2004 Microsoft Corporation. All rights reserved.
This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.