DEV310 Top 10 Tricks for a “Killer” Web Application
DEV310 Top 10 Tricks for a “Killer” Web Application
Paul D. SheriffPaul D. SheriffPDSA, Inc.PDSA, [email protected]@pdsa.com
Ken GetzKen GetzMCW Technologies, LLCMCW Technologies, LLC
[email protected]@mcwtech.com
Demos available for download in VB.NET and C# at:Demos available for download in VB.NET and C# at:http://www.mcwtech.com/2004/teched/us
Us.AboutUs.About
Paul D. SheriffPaul D. Sheriff
President of PDSA, Inc.President of PDSA, Inc.
www.pdsa.comwww.pdsa.com
Ken GetzKen GetzKNG Consulting, Inc.KNG Consulting, Inc.
www.mcwtech.com, www.mcwtech.com, www.developershandbook.comwww.developershandbook.com
Microsoft Regional Directors, Microsoft Regional Directors, SoCalSoCal
Addison-Wesley BookAddison-Wesley BookASP.NET Developer’s JumpstartASP.NET Developer’s Jumpstart
AssumptionsAssumptions
You are familiar with:You are familiar with:Programming in .NETProgramming in .NET
ASP.NETASP.NET
ADO.NETADO.NET
N-Tier conceptsN-Tier concepts
The demos are in VB.NETThe demos are in VB.NETAll concepts apply to C# as wellAll concepts apply to C# as well
Case StudyCase Study
TransamericaTransamericaDeveloped during .NET Beta 2 / .NET 1.0Developed during .NET Beta 2 / .NET 1.0
PDSA, Inc. helped them architect PDSA, Inc. helped them architect application for re-useapplication for re-use
Created standards for developmentCreated standards for development
These tips and tricks are from that projectThese tips and tricks are from that project
http://www.microsoft.com/casestudieshttp://www.microsoft.com/casestudies
Best Practices For Best Web SitesBest Practices For Best Web Sites
How do I… How do I… Create an n-tier design for my Web site?Create an n-tier design for my Web site?
Store and retrieve application settings?Store and retrieve application settings?
Create a dynamic and flexible Create a dynamic and flexible user interface?user interface?
Ensure common code runs each time a Ensure common code runs each time a page is loaded?page is loaded?
Track users’ actions throughout my Track users’ actions throughout my Web application?Web application?
Best Practices For Best Web SitesBest Practices For Best Web Sites
How do I… How do I… Track and notify tech support of Track and notify tech support of exceptions that occur?exceptions that occur?
Provide bullet-proof access to Provide bullet-proof access to Session variables?Session variables?
Ensure unexpected errors are handled Ensure unexpected errors are handled gracefully?gracefully?
Assign roles to users and secure Assign roles to users and secure Web pages?Web pages?
Provide the best performance?Provide the best performance?
DisclaimerDisclaimer
The code in this session is…The code in this session is…For demonstration and for teaching For demonstration and for teaching techniquestechniques
NOT production codeNOT production code
DemoDemo
Investigate the sampleInvestigate the sample
How Do I Create An N-Tier Design?How Do I Create An N-Tier Design?
Create N-Tier DesignCreate N-Tier Design
Create your own data layer Create your own data layer (Class Library) project(Class Library) project
Encapsulate all SQL in classesEncapsulate all SQL in classes
Return DataSets and DataReadersReturn DataSets and DataReadersTyped DataSetsTyped DataSets
Your own object that implements Your own object that implements IListSource or other bindable interfaceIListSource or other bindable interface
Create N-Tier DesignCreate N-Tier Design
Three ProjectsThree ProjectsUser InterfaceUser Interface
Business/Data LayerBusiness/Data Layer
Common ClassesCommon Classes
eNorthwindUI
NorthwindDataLayerBusiness/Data Layer
WebCommonCommon Web Classes
Create N-Tier DesignCreate N-Tier Design
Data LayerData LayerBase ClassBase Class
Contains ADO.NET codeContains ADO.NET code
Business/Data ClassesBusiness/Data ClassesSQL and Business rulesSQL and Business rules
OrdersDC
SqlHelperADO.NET Code
CategoriesDC ProductsDC
Create N-Tier DesignCreate N-Tier Design
For example, loading a DropDownListFor 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 DesignCreate N-Tier Design
Why is this important?Why is this important?Allows you to reuse data layer in desktop Allows you to reuse data layer in desktop applications, mobile Web apps, and moreapplications, mobile Web apps, and more
Gives you flexibility to change data Gives you flexibility to change data access method late in the access method late in the development processdevelopment process
Create N-Tier DesignCreate N-Tier Design
Why is this important?Why is this important?Centralizes SQLCentralizes SQL
No dependence on connections in UI layerNo dependence on connections in UI layer
Allows you to modify and tune SQL in Allows you to modify and tune SQL in one placeone place
Can switch from SQL statements to stored Can switch from SQL statements to stored proceduresprocedures
Create N-Tier DesignCreate N-Tier Design
Demo 1 of 9Demo 1 of 9
Things to look atThings to look atHomePage.aspx code that calls the data HomePage.aspx code that calls the data layerlayer
LoadCategories methodLoadCategories method
CategoriesDC and SqlHelper classesCategoriesDC and SqlHelper classes
How Do I Work With Application Settings?How Do I Work With Application Settings?
Work With Application SettingsWork With Application Settings
Use ConfigurationSettings.AppSettings Use ConfigurationSettings.AppSettings to get values from default to get values from default <appSettings> section<appSettings> section
Most people use this technique:Most people use this technique:
Can be slowCan be slowReads Web.Config file each timeReads Web.Config file each time
Reads one item at a timeReads one item at a time
ConfigurationSettings. _ AppSettings("ConnectString")
Work With Application SettingsWork With Application Settings
Create your own class that supplies Create your own class that supplies application settingsapplication settings
Use shared/static methods to Use shared/static methods to expose dataexpose data
Where might you store settings?Where might you store settings?Web.ConfigWeb.Config
XML fileXML file
RegistryRegistry
Database tableDatabase table
Work With Application SettingsWork 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 SettingsWork With Application Settings
Can create your own configuration Can create your own configuration section handlersection handler
Implement IConfigurationSectionHandlerImplement IConfigurationSectionHandler
See WebAppConfigSee WebAppConfig
IConfigurationSectionIConfigurationSection
WebAppConfig.ConnectString
Shared Sub New() ConfigurationSettings. _ GetConfig("AppConfig")End Sub
Shared Property ConnectString Return mConnectEnd Property
<configSections><section name="AppConfig" type="WebCommon.WebAppConfigHandler, WebCommon" /></configSections><AppConfig> <add key="ConnectString" value="..." /></AppConfig>
Function Create mConnect = nvc("ConnectString")End Sub
Class WebAppConfig
Work With Application SettingsWork With Application Settings
Why is this important?Why is this important?Flexibility to change data storage locationFlexibility to change data storage location
No need to rewrite all your code if No need to rewrite all your code if location changeslocation changes
Just rewrite the configuration classJust rewrite the configuration class
Work With Application SettingsWork With Application Settings
Demo 2 of 9Demo 2 of 9
Things to look atThings to look atWeb.Config fileWeb.Config file
WebAppConfig classWebAppConfig class
How Do I Create A Dynamic And Flexible User Interface?
How Do I Create A Dynamic And Flexible User Interface?
Maintainable User InterfaceMaintainable User Interface
User controls: best for application-User controls: best for application-specific user interfacespecific user interface
Server controls: best for Server controls: best for multi-application solutionsmulti-application solutions
Style sheets: for consistent UIStyle sheets: for consistent UI
Maintainable User InterfaceMaintainable User Interface
User ControlsUser ControlsHeadersHeaders
NavigationNavigationData-driven menu systemData-driven menu system
Repeated groups of controlsRepeated groups of controlsName, City, State, Postal CodeName, City, State, Postal Code
Phone number and extensionPhone number and extension
Maintainable User InterfaceMaintainable User Interface
Server ControlsServer ControlsDesign your own controlsDesign your own controls
Inherit from existingInherit from existingExtend with more functionalityExtend with more functionality
Maintainable User InterfaceMaintainable User Interface
Style SheetsStyle SheetsApply a style sheet to all pagesApply a style sheet to all pages
Makes global changes much easierMakes global changes much easier
Frameless designFrameless designCan use <Div> tagsCan use <Div> tags
Use style sheet for absolute positioningUse style sheet for absolute positioning
Maintainable User InterfaceMaintainable User Interface
Demo 3 of 9Demo 3 of 9
Things to look atThings to look atUser ControlsUser Controls
HeaderHeader
Data Driven Menu SystemData Driven Menu System
Style sheetStyle sheet<div> tag<div> tag
How Do I Ensure Common Code Runs Each Time A Page Is Loaded?
How Do I Ensure Common Code Runs Each Time A Page Is Loaded?
Create A Base Page ClassCreate A Base Page Class
Inherit from built-in Page classInherit from built-in Page classOverride OnLoadOverride OnLoad
Override OnErrorOverride OnError
Add custom methodsAdd custom methodsException PublishingException Publishing
User TrackingUser Tracking
More, as necessaryMore, as necessary
Create A Base Page ClassCreate 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 ClassCreate A Base Page Class
Why is this important?Why is this important?Ensure important code runs on each pageEnsure important code runs on each page
Track usersTrack users
Publish unexpected errorsPublish unexpected errors
Allows for flexibility in the futureAllows for flexibility in the future
Create A Base Page ClassCreate A Base Page Class
Demo 4 of 9Demo 4 of 9
Things to look atThings to look atHomePage.aspx (Inherits statement)HomePage.aspx (Inherits statement)
WebPageBase classWebPageBase class
How Do I Track Users’ Actions Throughout My Web Application?
How Do I Track Users’ Actions Throughout My Web Application?
Track Users’ ActionsTrack Users’ Actions
Override OnLoad in base page classOverride OnLoad in base page class
Create a table in your databaseCreate a table in your database
Track statisticsTrack statisticsUser NameUser Name
Page NamePage Name
Site NameSite Name
Date/TimeDate/Time
Track Users’ ActionsTrack Users’ Actions
Why is this important?Why is this important?Statistics on page visitsStatistics on page visits
Who went to which page and whenWho went to which page and when
Can use your database to track usageCan use your database to track usage
Can provide a web interface to statisticsCan provide a web interface to statistics
Can add additional info you wish to trackCan add additional info you wish to trackOrder numberOrder number
User Profile InfoUser Profile Info
Track Users’ ActionsTrack Users’ Actions
Demo 5 of 9Demo 5 of 9
Things to look atThings to look atWebPageBase.HandleUserTrackingWebPageBase.HandleUserTracking
How Do I Track And Notify Tech Support Of Exceptions That Occur?
How Do I Track And Notify Tech Support Of Exceptions That Occur?
Track ExceptionsTrack Exceptions
Microsoft Exception Management Microsoft Exception Management BlockBlock
Consistent approach to exception Consistent approach to exception managementmanagement
Add additional exception publishersAdd additional exception publishers
Turn publishers on and off dynamicallyTurn publishers on and off dynamically
Download from Microsoft’s siteDownload from Microsoft’s siteOne of several application blocksOne of several application blocks
Two assemblies are needed with Two assemblies are needed with your applicationyour application
Track ExceptionsTrack Exceptions
Steps to followSteps to follow1.1. Create your own exception publishersCreate your own exception publishers
2.2. Add support for publisher in Web.ConfigAdd support for publisher in Web.Config
3.3. Publish the exception using the Microsoft Publish the exception using the Microsoft Exception Management BlockException Management Block
Track ExceptionsTrack Exceptions
How do you do it?How do you do it?Create class that implements Create class that implements IExceptionPublisherIExceptionPublisher
Implement Publish methodImplement Publish methodWrite information to event log, database Write information to event log, database or e-mailor e-mail
Add necessary configuration information Add necessary configuration information to Web.Configto Web.Config
Within Catch block call Publish methodWithin Catch block call Publish method
Track ExceptionsTrack ExceptionsPrivate Sub LoadCategories() Dim dc As CategoriesDC
Try dc = New _ CategoriesDC(WebAppConfig.ConnectString) ' code omitted
Catch ex As Exception WebException.Publish(ex)
End TryEnd Sub
Track ExceptionsTrack Exceptions
Why is this important?Why is this important?Can track all errors that have occurred Can track all errors that have occurred on the siteon the site
Can receive email notification of errorsCan receive email notification of errors
Can add publishers at runtimeCan add publishers at runtime
Can receive additional information Can receive additional information about errorabout error
Stack traceStack trace
User Name, Page NameUser Name, Page Name
Other application variablesOther application variables
Track ExceptionsTrack Exceptions
Demo 6 of 9Demo 6 of 9
Things to look atThings to look atWeb.ConfigWeb.Config
WebException.Publish methodWebException.Publish method
WebCommon.EmSql and WebCommon.EmSql and EmEmail classesEmEmail classes
How Do I Provide Bullet-Proof Access To Session Variables?
How Do I Provide Bullet-Proof Access To Session Variables?
Work With Session VariablesWork With Session Variables
Normally, refer to session variables Normally, refer to session variables using string index into a collection:using string index into a collection:
Type the name wrong?Type the name wrong?You get the wrong infoYou get the wrong info
Values are loosely typedValues are loosely typedAlways returns ObjectAlways returns Object
txtCust.Text = Session("CustID").ToString()
Work With Session VariablesWork With Session Variables
To solve the problemTo solve the problemCreate class that “wraps up” access to Create class that “wraps up” access to Session variablesSession variables
Use Shared/static members to work with Use Shared/static members to work with SessionSession
Work With Session VariablesWork With Session Variables
Why is this important?Why is this important?Reduces runtime errorsReduces runtime errors
Allows IntelliSense while codingAllows IntelliSense while coding
Avoids type-casting issuesAvoids type-casting issues
Work With Session VariablesWork With Session Variables
Demo 7 of 9Demo 7 of 9
Things to look atThings to look atCustomersMain.aspxCustomersMain.aspx
WebSessionInfo classWebSessionInfo class
How Do I Ensure Unexpected Errors Are Handled Gracefully?
How Do I Ensure Unexpected Errors Are Handled Gracefully?
Handle Unhandled ExceptionsHandle Unhandled Exceptions
Override OnError method in base Override OnError method in base page classpage class
Use <customErrors> element in Use <customErrors> element in Web.ConfigWeb.Config
Handle Unhandled ExceptionsHandle Unhandled Exceptions
Why is this important?Why is this important?Provides design pattern for Provides design pattern for unhandled errorsunhandled errors
Allows you to publish unhandled errorsAllows you to publish unhandled errors
Ensures users do not see the default Ensures users do not see the default ASP.NET error pageASP.NET error page
Handle Unhandled ExceptionsHandle Unhandled Exceptions
Demo 8 of 9Demo 8 of 9
Things to look atThings to look atOnError event in WebPageBaseOnError event in WebPageBase
<customErrors> in Web.Config<customErrors> in Web.Config
How Do I Assign Roles To Users And Secure Web Pages?
How Do I Assign Roles To Users And Secure Web Pages?
Manage Security And RolesManage Security And Roles
Use Windows or Forms-based securityUse Windows or Forms-based security
Forms-based authenticationForms-based authenticationBest for Internet sitesBest for Internet sites
ASP.NET makes this very easyASP.NET makes this very easy
Windows-based authenticationWindows-based authenticationBest for Intranet/Extranet sitesBest for Intranet/Extranet sites
Manage Security And RolesManage Security And Roles
Modify Authentication and Modify Authentication and Authorization sections in Web.ConfigAuthorization sections in Web.Config
<authentication mode="Forms"> <forms name="eNorthwindCookieName" loginUrl="Admin/Login.aspx" /></authentication>
<authorization> <allow users="*" /></authorization>
Setting Security CookieSetting Security Cookie
If LoginValid() Then FormsAuthentication. _ RedirectFromLoginPage(txtLogin.Text, False)Else lblMessage.Text = "Invalid LoginID"End If
Manage Security And RolesManage Security And Roles
Why is this important?Why is this important?Secure a certain portion of your web siteSecure a certain portion of your web site
Grant users within roles access to Grant users within roles access to secured portions of your web sitesecured portions of your web site
Manage Security And RolesManage Security And Roles
Demo 9 of 9Demo 9 of 9
Things to look atThings to look atWeb.ConfigWeb.Config
<Authentication><Authentication>
<Authorization><Authorization>
<Location><Location>
Login.aspxLogin.aspx
CustomersMain.aspxCustomersMain.aspxIsInRoleIsInRole
Global.asaxGlobal.asaxApplication_AuthenticateRequestApplication_AuthenticateRequest
SummarySummary
OOP techniques are key to flexibilityOOP techniques are key to flexibility
User controls and style sheets can User controls and style sheets can make your web site much easier to make your web site much easier to customizecustomize
Create design pattern for error Create design pattern for error handlinghandling
Security important in every applicationSecurity important in every application
Compile your own tipsCompile your own tipsKeep them somewhere you can find themKeep them somewhere you can find them
Review regularlyReview regularly
Thanks for Coming!Thanks for Coming!
Paul D. SheriffPaul D. [email protected]@pdsa.com
Ken GetzKen [email protected]@mcwtech.com
Demos available at:Demos available at:http://www.mcwtech.com/2004/teched/ushttp://www.mcwtech.com/2004/teched/us
AppendixAppendix
How Do I Provide The Best Performance?How Do I Provide The Best Performance?
Improve PerformanceImprove Performance
Performance is a full session’s worth Performance is a full session’s worth of information!of information!
Many ways to optimizeMany ways to optimize
ADO.NETADO.NET
Caching techniquesCaching techniques
Optimization must be something you Optimization must be something you think about all the way through your think about all the way through your development cycledevelopment cycle
Improve PerformanceImprove Performance
ADO.NET TipsADO.NET TipsUse native providers, if possibleUse native providers, if possible
Use SqlClient instead of OleDbUse SqlClient instead of OleDb
Use a DataReader for loading Use a DataReader for loading drop-down listsdrop-down lists
Cache frequently used dataCache frequently used dataRead data from a database and store in XML Read data from a database and store in XML file on local file systemfile on local file system
Use stored proceduresUse stored procedures
Improve PerformanceImprove Performance
Cache User Controls if possibleCache User Controls if possible
Cache Pages that don’t change oftenCache Pages that don’t change often
Store ViewState on the serverStore ViewState on the serverMSDN Magazine (Dino Esposito’s article MSDN Magazine (Dino Esposito’s article Feb 2003)Feb 2003)
http://msdn.microsoft.com/msdnmag/issuhttp://msdn.microsoft.com/msdnmag/issues/03/02/CuttingEdge/default.aspxes/03/02/CuttingEdge/default.aspx
Improve PerformanceImprove Performance
Use HTML controls instead of server Use HTML controls instead of server controls for best performancecontrols for best performance
Use client-side scripting for validationUse client-side scripting for validationAvoids post backAvoids post back
Compile as "Release" before deploying Compile as "Release" before deploying to productionto production
Improve PerformanceImprove Performance
Don’t use Response.Redirect within Don’t use Response.Redirect within Try/Catch blockTry/Catch block
Can cause ThreadAbortExceptionCan cause ThreadAbortException
Exceptions are expensiveExceptions are expensive
Move outside the Try/Catch blockMove outside the Try/Catch block
Improve PerformanceImprove Performance
Use a custom class for reading values Use a custom class for reading values from Web.Configfrom Web.Config
Much faster than using AppSettingsMuch faster than using AppSettings
Reading from Registry is very slow!Reading from Registry is very slow!If you store config settings here, make If you store config settings here, make sure you cache them after readingsure you cache them after reading
Much slower than AppSettingsMuch slower than AppSettings
Improve PerformanceImprove Performance
Disable SessionState when not Disable SessionState when not neededneeded
By default, it’s always onBy default, it’s always on
Disable ViewState when not neededDisable ViewState when not neededBy default, it’s always onBy default, it’s always on
Can disable on a control or page levelCan disable on a control or page level
Use in-process session state Use in-process session state if possibleif possible
If you are not using a web farmIf you are not using a web farm
If you don't need redundancy/fail overIf you don't need redundancy/fail over
Improve PerformanceImprove Performance
Make sure you are checking Make sure you are checking Page.IsPostbackPage.IsPostback
Avoid running code each time back to Avoid running code each time back to a pagea page
Use buffered string accessUse buffered string accessStringWriter or StringBuilderStringWriter or StringBuilder
Avoid making calls to Avoid making calls to COM componentsCOM components
Rewrite using managed code, if possibleRewrite using managed code, if possible
Attend a free chat or web castAttend a free chat or web casthttp://www.microsoft.com/communities/chats/default.mspxhttp://www.microsoft.com/communities/chats/default.mspx http://www.microsoft.com/usa/webcasts/default.asphttp://www.microsoft.com/usa/webcasts/default.asp
List of newsgroupsList of newsgroupshttp://communities2.microsoft.com/http://communities2.microsoft.com/communities/newsgroups/en-us/default.aspxcommunities/newsgroups/en-us/default.aspx
MS Community SitesMS Community Siteshttp://www.microsoft.com/communities/default.mspxhttp://www.microsoft.com/communities/default.mspx
Locate Local User GroupsLocate Local User Groupshttp://www.microsoft.com/communities/usergroups/default.mspxhttp://www.microsoft.com/communities/usergroups/default.mspx
Community sitesCommunity siteshttp://www.microsoft.com/communities/related/default.mspxhttp://www.microsoft.com/communities/related/default.mspx
Q1:Q1: Overall satisfaction with the sessionOverall satisfaction with the session
Q2:Q2: Usefulness of the informationUsefulness of the information
Q3:Q3: Presenter’s knowledge of the subjectPresenter’s knowledge of the subject
Q4:Q4: Presenter’s presentation skillsPresenter’s presentation skills
Q5:Q5: Effectiveness of the presentationEffectiveness of the presentation
Please fill out a session evaluation on CommNetPlease fill out a session evaluation on CommNet
© 2004 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.