Things Every ASP.NET Developer Should Know

Download Things Every ASP.NET Developer Should Know

Post on 23-Feb-2016




0 download


Things Every ASP.NET Developer Should Know. Robert Boedigheimer. About Me. MCPD ASP.NET Developer 3.5 MCPD Web, Charter Member MCSD .NET, Early Achiever Web developer since 1995 Columnist for Wrox Author ASP.NET MVP - PowerPoint PPT Presentation


Improving ASP.NET User Interfaces with the AJAX Control ToolkitThings Every ASP.NET Developer Should KnowRobert BoedigheimerAbout MeMCPD ASP.NET Developer 3.5MCPD Web, Charter MemberMCSD .NET, Early AchieverWeb developer since 1995Columnist for aspalliance.comWrox AuthorASP.NET MVP MonitorIIS Logs, LogParserIE Developer ToolbarHTTP CompressionContent ExpirationsAjax MinifierEtagsCSS SpritesASP.NETTracingConfigurationApplication_Error( )Safe FunctionsPage Control TreeValidation ControlsCachingSession and TimeoutsAdaptersTechniquesHTTPHypertext Transfer ProtocolProtocol defined in RFC 2068 (Http 1.1), January 1997Request/response paradigmHeader and body RequestGET http://localhost:99/default.aspx HTTP/1.1Accept: */*Accept-Language: en-usUA-CPU: x86Accept-Encoding: gzip, deflateUser-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 1.1.4322; InfoPath.2; .NET CLR 3.5.21022)Host: localhost:99Proxy-Connection: Keep-AlivePragma: no-cache5Multiple method types GET, POST (forms)User-Agent client agent type (IE browser, version), disturbing that your .Net version is transmittedHost DNS name of web site (host headers for web site sharing)Http ResponseHTTP/1.1 200 OKCache-Control: privateContent-Type: text/html; charset=utf-8Server: Microsoft-IIS/7.0X-AspNet-Version: 2.0.50727X-Powered-By: ASP.NETDate: Sun, 07 Mar 2010 19:22:19 GMTContent-Length: 686Home Page body {background-color:Green;} Home 6200 HTTP statusServer type and version of web server (possible to mask)Content-Type MIME type of data, used by client to know how to interpret response contentsBody that includes the specified content (of the given content type)FiddlerTracing tool specifically for HTTPShows complete request and response (not packets)Can save archive of sessionCan be used on own machine (ipv4.fiddler, ipv6.fiddler)Can create own GET requestsCan decrypt SSL traffic! Tool developed by Eric Lawrence of Microsoft Troubleshoot problems (404, 3rd party issues) Useful to archive off before and after for historical purposes7Fiddler (Transfer Timeline) Great visual to demonstrate what takes time on page requests, which files are too big, that we have too many 80-90% of pages times today are due to components (CSS, js, images)8Microsoft Network MonitorGeneral network tracing tool for many protocolsHooks into network adaptersSee network frames at multiple levelsApply filters for specific protocols, IP addresses, etc Log FilesTime Taken (execute, queue, and time to client IIS 7/6)Sub-status codes are very useful for indicating the exact problemsLog entries are made AFTER the page execution is completeLog file entries are always in GMTSetup cookie, referrer, bytes sent IIS 6 started using general status codes to hide what is actually going on Need a sub-status code to get the exact details ( MIME type not defined, get a 404 (not found) if check it will be a 404.3 which means the MIME type is not configured10IIS Log File ConfigurationLog ParserUtility to query IIS log files, event logs, etcQuery syntax nearly identical to SQLWrite series of queries for site health (HTTP status, time taken, file sizes, down pages, orders, etc)ASP.NET Response.AppendToLog( ) Headers for columns are in the IIS log file itself Help with logParser.exe /? AppendToLog( ) write out customer number or other id to help find records related to the user Also search by session id or client IP12Microsoft IE Developer ToolbarIncluded in IE 8See what styles are applied to elementsScript debugging, profilingResize the browser to various resolutionsDisable script, CSSLinks to validator for HTML, CSS, accessibility (IE 7) Know that anyone with IE 8 will have the tools (dont need to install and get blamed for everything!)13HTTP CompressionServer evaluates the Accept-Encoding header for request, compresses resulting responselargeGridView.aspx - 41 frames down to 7Implemented in February 2003 when about 3% of Fortune 1000 web sites utilizedUsed 53% less bandwidth, ~25% faster Keynote measurementsNow use IIS Compression (free)HTTP Compression (cont)IIS 7Can control when to stop using if CPU usage is too highMinimum default file size is 256KOnly static compression is on by defaultDetailed article about enabling IIS 6 compression at port80software.com15Content ExpirationsClient asks if-modified-sinceSmall content files it is just as expensive to see if modified as to receive contentSetup expiration times for content foldersAvoid requests for files that seldom change (.js, .css, images, etc)Rename the file if need to override browser cachingContent Expirations (cont)Ajax MinifierMicrosoft Ajax Minifier ( CSS and JavaScript filesRemove whitespace, comments, excessive semicolons, etcCommand line, .dll, and build tasksjQuery-1.4.2.js minimized 55.5%Test after minimize!MSBuild Extension Pack (version #) C:\Program Files (x86)\Microsoft\Microsoft Ajax Minifier 4>ajaxmin c:\inetpub\wwwroot\thingsToKnow\js\jquery-1.4.2.js -out jquery-1.4.2.ajaxMin.js18ETagsUsed for cache validationIIS sends the ETag header in response for static fileshash:changeNumberIIS 6changeNumber specific to serverSet to 0 with Metabase Explorer, 7changeNumber - 0 by defaultCompletely remove header with HttpModule People suggested adding own header Etag with value , but this did not work on IIS 719CSS SpritesCombine small images into a single imageUse CSS to index into the larger imageOften 70-95% of time taken for a user is time requesting components (images, .css, .js)Reduce the number of requests Most often the single image is smaller than the sizes added together20TracingSetup ASP.NET to save information about recent requests/Trace.axdConfiguration (machine.config only)External config files (no restart) customErrors mode=off looks really bad and reveals too much information compilation debug=true caused us production memory problems tracing enabled=true reveals too much information about requests22Global.asax Application_Error( )Every ASP.NET web site should have this coded to ensure that unhandled exceptions are caught and logged\HKLM\System\CurrentControlSet\Services\EventLog\Application and add key for sourceUse to redirect to a down page Only use a local try/catch if you can recover from the situation (much less code required)23Safe FunctionsProduction problems with Object Reference Not SetCaused by a reference type with null valueOften difficult to pinpoint cause Coding more safely is viewed as too much work (hurts productivity)Goal is to keep code concise yet get better diagnosticsPage Control TreeASP.NET creates objects for controls used on the page (including literal content) and stores in a treeCan view the tree using trace.axdReleased after the response is created for the clientRecursive generic processingValidation ControlsOWASP Top 10XSS (Cross Site Scripting)SQL InjectionAll input from web controls needs to be verifiedLeverage client validation for user experience but must validate on the serverCommon validatorsRequiredFieldValidatorRangeValidatorRegularExpressionValidatorCompareValidatorCustomValidatorCachingData caching (Cache), cut 50% of our SQL queries which was 72,080,000 less queries each month!SubstitutionOutput caching (shared)Dont cache page (set specific cache ability)Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);Session and TimeoutsCookie sent after initial request, uses to lookup the information, gets all session dataEnableSessionState None (module does not need to retrieve), ReadOnly (inProcess still modified)Timeout detection code ReadOnly does not write information back to the session store28AdaptersProvide an alternative rendering or behavior for controls or pagesOriginally designed to facilitate development of mobile web sites Wanted one set of controls that would render appropriately based on the user agent deviceDropped after ASP.NET 2.0 Beta 1Browser capabilities moved out to .browser filesVisual Studio designer does not display alternate renderingModify without altering existing code ASP.NET 2.0 CSS Friendly Adapters render with more CSS friendly output for many built in ASP.NET controls (menu, treeview, gridview, etc)29Miscellaneous ASP.NETRequest.SaveAs( )Context.ItemsResponse.AppendToLog( )App_offline.htmTechniquesPrototype designsFeedback before deep into design/implementationDetermine if riskier areas workTake it out of the page and try in isolated area (MUCH easier to debug!)Stub web service methods for data Give prototype to customer to get a feel for flow, navigation, experience SOA we agree to the intended output from web service, developer hardcodes and delivers to client developer can work then implements the actual method Parallelism Can quickly see what wont work well for client developer Easy to see whose fault it is when get final product31Useful SitesHTML Validation ( Validation ( ( (Learn tab -> videos)www.iis.netwww.aspalliance.comSummaryUnderstand how HTTP worksLearn about IISUse compression and expirationsLeverage tools to debug and understand how things work (solve many of your own problems)Utilize more ASP.NET techniquesQuestions