ASP.NET 2.

0 Tips and Tricks
Scott Guthrie General Manager Microsoft Developer Division scottgu@microsoft.com http://weblogs.asp.net/scottgu

Agenda
• • • • • Visual Studio Project Tips/Tricks ASP.NET UI Tips/Tricks ASP.NET AJAX Tips/Tricks ASP.NET Caching Tips/Tricks ASP.NET Deployment Tips/Tricks

Download Slides + Demos

http://weblogs.asp.net/scottgu

Visual Studio Project Tips and Tricks

VS 2005 Web Project Options
• VS 2005 Web Site Project Model
• File-system based project model

• VS 2005 Web Application Project Model
• Project-file based project model

• Which is best for you?
• Depends on your development style/preferences

Tips for Optimizing VS 2005 Web Site Build Performance
• 1) Verify no “dueling assembly reference” conflicts
• Can occur when .refresh files under \bin point to assemblies with version conflicts

• 2) Change project build settings:
• Modify F5 to be “Build Page” not “Build Site” • No longer have site build as part of solution

• Read my full blog posting here:
• http://weblogs.asp.net/scottgu/archive/2006/09/22/Tip_2 F00_Trick_3A00_-Optimizing-ASP.NET-2.0-WebProject-Build-Performance-with-VS-2005.aspx

Optimizing Build Performance

ASP.NET UI Tips/Tricks

Default Button
• Enable developers to identify default button behavior when the “enter” key is hit
• Cross browser: works with all modern browsers

• Can be set on <form> control to identify default for the form
• <form defaultbutton=“Button1” runat=server>

• Can also be set on <asp:panel> control to override form behavior when an input control has focus in the browser

Default Button Example:
<html> <body> <form defaultbutton=“button1” runat=“server”> <asp:button id=“button1” text=“Same Page” runat=“server”/> <asp:panel defaultbutton=“button2” runat=“server”> <asp:textbox id=“foo” runat=“server”/> <asp:button id=“button2” runat=“server”/> </asp:panel> </form> </body> </html>

Default Focus
• Enable developers to identify default focus behavior when page is loaded
• Cross browser: works with all modern browsers

• Can be set on <form> control to identify default for the form
• <form defaultfocus=“Textbox1” runat=server>

• Can also be programmatically set:
• Page.SetFocus(control) • TextBox.Focus()

Default Focus Example:
<html> <body> <form defaultfocus=“textbox2” defaultbutton=“button1” runat=“server”> <asp:textbox id=“textbox1” runat=“server”/> <asp:textbox id=“textbox2” runat=“server”/> <asp:button id=“button1” text=“Same Page” runat=“server”/> <asp:panel defaultbutton=“button2” runat=“server”> <asp:textbox id=“foo” runat=“server”/> <asp:button id=“button2” runat=“server”/> </asp:panel> </form> </body> </html>

SetFocusOnError
• Enable developers to force focus on a control when a validation error occurs
• Set as a property on the validation control
<asp:TextBox ID="TextBox3“ runat="server“ /> <asp:RequiredFieldValidator SetFocusOnError="true" ErrorMessage="TextBox3 is empty" ControlToValidate="TextBox3" runat="server“/>

Default Button and Focus

Clean HTML using CSS Adapters
• ASP.NET 2.0 introduced Control Adapter API
• Enables developers to override rendering of controls • Does not change the control’s API

• CSS Adapter Toolkit
• Free download from http://www.asp.net/ • New CSS Adapters Now support 11 Controls:
• • • • Menu, TreeView DataList, GridView, FormView, DetailsView Login, ChangePassword, PasswordRecovery CreateUserWizard, LoginStatus

• Ships with both VB and C# control adapter source

CSS Control Adapters

Web.Config Registration of Controls
• Server controls can now be registered within web.config files instead of on every page • Full Visual Studio support w/ intellisense
<!-- Web.Config --> <controls> <add tagPrefix="acme" tagName="uc" src="controls/uc.ascx" /> <add tagPrefix="my" namespace="MyControls.Basic" assembly="MyControls" /> </controls>

Control Registration in Web.config

Server Side Comments
• Useful feature for preventing server code/controls from running on HTML being sent to the server:
<%-Everything in here commented out --%>

• Useful tip: VS has a comment/uncomment toolbar menu item in source mode

Server Side Comments

ASP.NET AJAX Tips/Tricks

ASP.NET AJAX
• ASP.NET AJAX 1.0
• Fully supported product on top of ASP.NET 2.0

• ASP.NET AJAX Control Toolkit
• Library of free ASP.NET AJAX controls/extenders

• ASP.NET AJAX “Futures” CTP
• Features not quite ready to bake into the core • Go-Live license for deployment

ASP.NET AJAX Control Toolkit
• Separate download from core ASP.NET AJAX
• Great library of free ASP.NET AJAX enabled controls • Download from http://ajax.asp.net/

• Developed using a collaborative source model
• All source freely available with modification license • Both Microsoft & non-Microsoft developers can contribute

• Already contains 30 really cool controls
• Goal is to get 50-100 great controls over the next months

AJAX Control Extenders
• Controls that can AJAX-enable existing HTML UI and ASP.NET Server Controls
<asp:LinkButton ID=“ShowHideBtn" runat="server">Details...</asp:LinkButton> <asp:Panel ID="detailsPanel" runat="server" CssClass="DetailsPanel"> Blah, Blah, Blah <br /> Blah, Blah, Blah <br /> Blah, Blah, Blah </asp:Panel> <ajaxToolkit:CollapsiblePanelExtender TargetControlID="detailsPanel“ CollapseControlID="ShowHideBtn" ExpandControlID="ShowHideBtn" Collapsed="true" SuppressPostBack="true" runat="server“ />

PopUpControlExtender and CollapsablePanelExtender

Some of the AJAX Control Toolkit Extenders
• • • • • • • • • • AutoCompleteTextBoxExtender CollapsablePanelExtender AnimationExtender ConfirmButtonExtender DragPanelExtender DropShadowExtender AlwaysVisibleExtender DynamicPopulateExtender FilteredTextBoxExtender HoverMenuExtender • • • • • • • • • • • ModalPopupExtender MutuallyExclusiveCheckboxExtender NumericUpDownExtender PasswordStrengthExtender PopUpControlExtender ResizableControlExtender RoundedCornersExtender SliderExtender TextBoxWaterMarkExtender UpdatePanelAnimationExtender ValidatorCalloutExtender

AJAX Control Toolkit Extenders

Building your own Extenders
• ASP.NET AJAX “Core” includes classes needed to build your own extenders
• ExtenderControlBase class • JavaScript framework for encapsulating classes • AJAX network hooks and postback integration

• Check out the existing control extenders in the ASP.NET AJAX Control Toolkit to learn more

ASP.NET AJAX Client Library
• Rich JavaScript library support
• JavaScript Type System • JavaScript Network Serialization Stack • Helper functions and common libraries

• Enables you to easily add custom JavaScript to your site (go to the metal)

Custom AJAX UI Templating

Two Tips
• Enable debug ASP.NET AJAX Scripts for better debugging and validation
• <compilation debug=“true”/> in web.config

• Use debugger keyword in code to enable rapid breakpointing

ASP.NET Caching Tips/Tricks

Output Caching
• Super powerful area of ASP.NET • Not nearly enough developers use it • Virtually every application can benefit from it

Page Output Caching
• Cache entire page output on the server and re-use across multiple web requests • Declaratively enable it via page directive:
• • • • <%@ OutputCache Duration=“10” varybyparam=“none” <%@ OutputCache Duration=“10” varybyparam=“categoryid” %> <%@ OutputCache Duration=“10” varybycontrol=“category” %> <%@ OutputCache Duration=“10” varybycustom=“mymethod” %>

• Or Programmatically set it via code:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.VaryByParams[“categoryid"] = true;

Partial Page Output Caching
• Cache regions of a page encapsulated within a user control (.ascx file) or server control • Ideal for cases where you have a region of cacheable data/output within an otherwise dynamic page • Declaratively enable:
• • <%@ OutputCache Duration=“10” varybyparam=“none” %> <%@ OutputCache Duration=“10” varybyparam=“none” shared=“true” %>

Page and Partial-Page Caching

Substitution Control
• New feature with ASP.NET 2.0 • Enables you to cache everything on a page except for indicated regions • Controlled by adding control marker:
• <asp:substitutioncontrol methodname=“MyStaticMethod” /> public static string MyStaticMethod(HttpContext context) { return “Dynamic value”; }

Substitution Control

SQL Cache Invalidation
• New feature with ASP.NET 2.0 • Enables you to cache items until a backend database change occurs • Ensures data within site is always fresh
• No need to wait for timeout to occur

• Polling model with SQL 2000, push model with SQL 2005

SQL Cache Invalidation

Web.Config CacheProfiles
• New feature with ASP.NET 2.0 • Output Caching configuration can now be managed within web.config via CacheProfiles
<!-- Web.Config --> <caching> <outputCacheSettings> <outputCacheProfiles> <add name="ProductPages" duration="50000" /> </outputCacheProfiles> </outputCacheSettings> </caching>

ASP.NET Deployment Tips/Tricks

App_Offline.htm
• Enables you to gracefully take a server application “offline” for maintenance • Add “app_offline.htm” file at app root
• Useful when making big changes/upgrades • 1) Causes ASP.NET app to shutdown • 2) Causes all dynamic requests to return app_offline.htm file contents

• Tip: Make sure the app_offline.htm file is large enough (512 bytes) to disable the IE “friendly http errors” feature

App_Offline.htm

Always deploy Debug=“false”
• Common mistake is to deploy ASP.NET apps with <compilation debug=“true”/> set • Bad consequences:
• Debug compilation slows performance • App uses much more memory • Client-side scripts are not cached

• Always, Always make sure it is off
• VS 2005 Web Deployment Projects can help

<deployment retail=“true”/>
• Consider disabling debug=“true” on a production server by configuring the below setting in the machine.config file:
<configuration> <system.web> <deployment retail=”true”/> </system.web> </configuration>

One last Tip/Trick to Stay Up to Date

RSS
• Flexible, open, format for sharing information
• Blogs, Newspapers, Events, Amazon Wishlists, etc. • Also useful for sharing information w/ customers

• ASP.NET RSS Toolkit makes RSS super easy
• • • • Enables developers to subscribe to RSS feeds Enables developers to publish RSS feeds Integrated caching engine Download from: http://blogs.msdn.com/dmitryr

RSS Toolkit Example
<h1>Recent ScottGu Posts</h1> <asp:DataList ID="MyFeeds" DataSourceID="MyRssFeed" runat="server"> <ItemTemplate> <a href='<%# Eval("link") %>'> <%# Eval("title") %> </a> </ItemTemplate> </asp:DataList> <RssToolkit:RssDataSource ID="MyRssFeed" Url="http://weblogs.asp.net/scottgu/Rss.aspx" MaxItems="10" runat="server" />

RSS Reader

Summary
• Enormous number of new features in ASP.NET 2.0
• Tons of additional cool features out there…

• Visit the http://www.asp.net/ quickstarts to try out hundreds of samples online • Download these slides+demos from: http://weblogs.asp.net/scottgu

© 2003-2004 Microsoft Corporation. All rights reserved.
This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

Format Databind Expressions
• Enable richer custom formatting expressions • Avoids complicating .aspx markup:
<asp:datalist id=“datalist1” runat=“server”> <ItemTemplate> Value: <%# FormatPrice(Eval(“columnname”)) %> </ItemTemplate> </asp:datalist> Public Function FormatPrice(ByVal value As Double) As String If (value > 15) Then Return "<span class='expensive'>$" & value & "</span>" Else Return "$" & value End If End Function

Custom Databinding Expressions

Default Button
• Enable developers to identify default button behavior when the “enter” key is hit
• Cross browser: works with all modern browsers

• Can be set on <form> control to identify default for the form
• <form defaultbutton=“Button1” runat=server>

• Can also be set on <asp:panel> control to override form behavior when an input control has focus in the browser

Default Button Example:
<html> <body> <form defaultbutton=“button1” runat=“server”> <asp:button id=“button1” text=“Same Page” runat=“server”/> <asp:panel defaultbutton=“button2” runat=“server”> <asp:textbox id=“foo” runat=“server”/> <asp:button id=“button2” runat=“server”/> </asp:panel> </form> </body> </html>

Default Focus
• Enable developers to identify default focus behavior when page is loaded
• Cross browser: works with all modern browsers

• Can be set on <form> control to identify default for the form
• <form defaultfocus=“Textbox1” runat=server>

• Can also be programmatically set:
• Page.SetFocus(control) • TextBox.Focus()

Default Focus Example:
<html> <body> <form defaultfocus=“textbox2” defaultbutton=“button1” runat=“server”> <asp:textbox id=“textbox1” runat=“server”/> <asp:textbox id=“textbox2” runat=“server”/> <asp:button id=“button1” text=“Same Page” runat=“server”/> <asp:panel defaultbutton=“button2” runat=“server”> <asp:textbox id=“foo” runat=“server”/> <asp:button id=“button2” runat=“server”/> </asp:panel> </form> </body> </html>

SetFocusOnError
• Enable developers to force focus on a control when a validation error occurs
• Set as a property on the validation control
<asp:TextBox ID="TextBox3“ runat="server“ /> <asp:RequiredFieldValidator SetFocusOnError="true" ErrorMessage="TextBox3 is empty" ControlToValidate="TextBox3" runat="server“/>

Default Button and Focus