1 / 55

ASP.NET Best Practices

ASP.NET Best Practices. Phil Wolfe, pwolfe@quilogy.com MCSD, MCDBA, MCT, MCP+SB MidNET User Group President. Upgrading Performance User Interaction Maintenance Architecture Design. Configuration Scalability Security Authentication Authorization Deployment. Agenda Best Practices for:.

britannia
Télécharger la présentation

ASP.NET Best Practices

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ASP.NET Best Practices Phil Wolfe, pwolfe@quilogy.com MCSD, MCDBA, MCT, MCP+SB MidNET User Group President

  2. Upgrading Performance User Interaction Maintenance Architecture Design Configuration Scalability Security Authentication Authorization Deployment AgendaBest Practices for:

  3. 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

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

  5. Demo Page Output Caching • 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

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

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

  8. 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

  9. 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

  10. Use appropriate data access • Use Correct Data Client • SQL Client for SQL • Oracle client for Oracle • Use correct access object • 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;)

  11. 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 

  12. Best Practices for User Interaction • Using Server controls • Implement error pages and events • Using IE specific features • Using Cookieless sessions • Smart Navigation

  13. 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 themex. Small search bar on every page since it posts somewhere else.

  14. Demo ASP.NET Errors • 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)

  15. IE Specific Features • Treeview • Buttonbar • Tabstrip • Multipage • 3rd-Party • Found at:www.123ASPX.comwww.codeproject.comwww.411asp.net

  16. Cookieless Sessions <sessionState cookieless=“true” /> • Munges the session id in the URL:http://server/(lit3py55t21z5v55vlm25s55)/vdir/SessionState.aspx • Must use relative URLs in app • Works on devices that don’t support cookies

  17. Demo Smart Navigation • 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

  18. Best Practices for Maintenance • User Controls • Debugging and Tracing • Web.Config • Codebehinds • Page Directives

  19. 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)

  20. 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

  21. Web.Config • XML configuration file • 1 per directory • Settings are inherited and unioned • Many different settings can be set • Doesn’t require a recompile unlike the global.asax • See help for available settings • Can be edited on the fly from anywhere

  22. Demo Codebehinds • 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>

  23. Page Directives • Buffer = “true” • EnableSessionState = “true” • EnableViewState = “true” • Explicit = “false” • Strict = “false” • Trace = “false” • These are the defaults (consider reversing)

  24. 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

  25. 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.

  26. 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.

  27. BusinessLogic Good Business Logic Use • Do not call YOUR Web Services from YOUR Web Application. – Call the Business Logic Directly Web Service ASPX DB

  28. 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

  29. 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

  30. 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

  31. 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

  32. Custom Configuration Handler • If you want your own web.config section apart from appSettings • Implement iConfigurationSectionHandler • Register in <configSection> • See Help

  33. Location attribute • To apply settings to a specific section of your application. <configuration> <location path=“myvdir”> <system.web> …Specific config… </system.web> </location </configuration>

  34. Protect passwords • With forms auth you can store passwords in web.config • Store them with encryption so they can’t be stolen

  35. Best Practices for Scalability • Session state considerations • Web services • Components • Connection pooling in ASP.NET

  36. 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

  37. 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

  38. Components • Components can exist on other machines running in Component Services • Use .NET Remoting to access them

  39. 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

  40. Best Practices for Security • IIS gets request first so pass it to ASP.NET • Impersonate • Implement custom HTTPModules

  41. 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

  42. 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" />

  43. Demo Custom HTTPModules • 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

  44. Best Practices for Authentication • Windows Authentication • Forms Authentication • Custom Authentication

  45. Demo 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

  46. 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??

  47. 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

  48. 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

  49. Best Practices for Deployment • Performance counters • Stress testing with Application Center Test • Correct encryption keys in web.config • Set Process model recovery

  50. Demo 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

More Related