640 likes | 1.35k Views
ASP.NET Tips and Tricks. Russ Fustino Microsoft Corporation. What we will cover. Development Tips and Tricks Error Handling Tips and Tricks Production Tips and Tricks. Session Prerequisites. ASP Basic knowledge of ASP.NET. Level 300. Agenda. Development Tips and Tricks
E N D
ASP.NET Tips and Tricks Russ Fustino Microsoft Corporation
What we will cover • Development Tips and Tricks • Error Handling Tips and Tricks • Production Tips and Tricks
Session Prerequisites • ASP • Basic knowledge of ASP.NET Level 300
Agenda • Development Tips and Tricks • Error Handling Tips and Tricks • Production Tips and Tricks
Development Tips And Tricks File upload • ASP.NET provides built-in file upload support • No posting acceptor required • No third party components required • Accessible through two APIs: • Request.Files collection • <input type=file> server control • HttpPostedFile Object: • HttpPostedFile.InputStream • HttpPostedFile.ContentType • HttpPostedFile.FileName • HttpPostedFile.SaveAs(fileLocation)
Development Tips And Tricks File upload example <html> <script language="VB" runat=server> Sub Btn_Click(Sender as Object, E as EventArgs) UploadFile.PostedFile.SaveAs("c:\foo.txt") End Sub </script> <body> <form enctype="multipart/form-data" runat=server> Select File To Upload: <input id="UploadFile" type=file runat=server> <asp:button OnClick="Btn_Click“ runat=server/> </form> </body> </html>
Development Tips And Tricks Richer file upload • File system is not the only option • Example: Storing within SQL • Access uploaded file as byte array • Store file within SQL as image (blob) • Store ContentType and ContentLength also • Provide “Edit Link” to display page • Edit Link Page sets ContentType header and then writes binary array back to client
Development Tips And Tricks Image generation • Rich server image generation • Additionally supports resizing & cropping • Overlays on top of existing images • Read/Write Any Standard IO Stream • System.Drawing • Dynamically generate GIFs/JPGs from .aspx • Set ContentType appropriately • Optionally output cache results
Development Tips And Tricks ASP.NET XML Server Control • ASP.NET <asp:xml runat=server> • Enables output of XML • Enables optional XSL/T transform of XML • Binding options • File system • Database item • Built-in caching • Ensure efficient re-use • Improves performance
Development Tips And Tricks <ASP:XML> file sample <html> <body> <asp:xml id="MyXml1" DocumentSource="SalesData.xml" TransformSource="SalesChart.xsl" runat=server /> </body> </html>
Development Tips And Tricks <ASP:XML> data sample <%@ Page ContentType="text/xml" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SQLClient" %> <%@ Import Namespace="System.Xml" %> <script language="VB" runat=server> Sub Page_Load(Sender as Object, E as EventArgs) Dim conn as New SqlConnection(connectionString) Dim cmd as New SqlDataAdapter(“select * from products", conn) Dim dataset As New DataSet() cmd.Fill (dataset, "dataset") Dim XmlDoc as XmlDocument = New XmlDataDocument(dataset) MyXml1.Document = XmlDoc End Sub </script> <asp:xml id="MyXml1" runat=server/>
Development Tips And Tricks App settings • Application specific settings • Stored in web.config files • Enables devs to avoid hard-coding them • Administrators can later change them • Examples: • Database Connection String • MSMQ Queue Servers • File Locations
Development Tips And Tricks App settings steps • Create “web.config” file in app vroot: • To return value: Configuration.AppSettings(“dsn”) <configuration> <appSettings> <add key=“dsn” value=“localhost;uid=sa;pwd=;Database=foo”/> </appSettings> </configuration>
Development Tips And Tricks Cookieless sessions • Session State no longer requires client cookie support for SessionID • Can optionally track SessionID in URL • Requires no code changes to app • All relative links continue to work
Development Tips And Tricks Cookieless sessions steps • Create “web.config” file in app vroot • Add following text: <configuration> <system.web> <sessionState cookieless=“true”/> </system.web> </configuration>
Development Tips And Tricks Smart navigation • Eliminates browser flicker/scrolling on browser navigation • Smooth client UI – but with server code • Automatic down-level for non-IE browsers • No client code changes required • <%@ Page SmartNavigation=“true” %> • Alternatively set in web.config file
Agenda • Development Tips and Tricks • Error Handling Tips and Tricks • Production Tips and Tricks
Error Handling Tips And Tricks Page tracing • ASP.NET supports page and app tracing • Easy way to include “debug” statements • No more messy Response.Write() calls! • Great way to collect request details • Server control tree • Server variables, headers, cookies • Form/Querystring parameters
Error Handling Tips And Tricks Page tracing steps • Add trace directive at top of page <%@ Page Trace=“True” %> • Add trace calls throughout page Trace.Write(“Button Clicked”) Trace.Warn(“Value: “ + value) • Access page from browser
Error Handling Tips And Tricks Application tracing steps • Create “web.config” file in app vroot: • Access tracing URL within app • http://localhost/approot/Trace.axd <configuration> <system.web> <trace enabled=“true” requestLimit=“10”/> </system.web> </configuration>
Error Handling Tips And Tricks Error handling • .NET provides unified error architecture • Runtime errors done using exceptions • Full call stack information available w/ errors • Can catch/handle/throw exceptions in any .NET Language (including VB) • ASP.NET also provides declarative application custom error handling • Enable programmatic logging of problems • Automatically redirect users to error page when unhandled exceptions occur
Error Handling Tips And Tricks Application_Error • Global application event raised if unhandled exception occurs • Provides access to current Request • Provides access to Exception object • Enables developer to log/track errors • Cool Tip: • Use new EventLog class to write custom events to log when errors occur • Use new SmtpMail class to send email to administrators
Error Handling Tips And Tricks Sending SMTP mail <%@ Import Namespace=“System.Web.Mail" %> <script language="VB" runat=server> Sub Application_Error(sender as Object, e as EventArgs) Dim MyMessage as New MailMessage MyMessage.To = “someone@microsoft.com" MyMessage.From = "MyAppServer" MyMessage.Subject = "Unhandled Error!!!" MyMessage.BodyFormat = MailFormat.Html MyMessage.Body = "<html><body><h1>" & Request.Path & _ "</h1>" & Me.Error.ToString() & "</body></html>" SmtpMail.Send(MyMessage) End Sub </script>
Error Handling Tips And Tricks Custom errors • Enable easy way to “hide” errors from end-users visiting a site • No ugly exception error messages • Enables you to display a pretty “site under repair” page of your design • Custom Errors configured within an application web.config configuration file • Can be configured per status code number • Can be configured to only display remotely
Error Handling Tips And Tricks Custom error page steps • Create “web.config” file in app vroot: <configuration> <system.web> <customErrors mode=“remoteonly” defaultRedirect=“error.htm”> <error statusCode=“404” redirect=“adminmessage.htm”/> <error statusCode=“403” redirect=“noaccessallowed.htm”/> </customErrors> </system.web> </configuration>
Agenda • Development Tips and Tricks • Error Handling Tips and Tricks • Production Tips and Tricks
Production Tips And Tricks Performance counters • Per Application Performance Counters • Enable easily monitoring of individual ASP.NET applications • Custom Performance Counters APIs • Now possible to publish unique application-specific performance data • Great for real-time application monitoring • Example: total orders, orders/sec
Production Tips And Tricks Process model recovery • ASP.NET runs code in an external worker process – aspnet_wp.exe • Automatic Crash Recovery • Automatic Memory Leak Recovery • Automatic Deadlock Recovery • Can also proactively configure worker process to reset itself proactively • Timer based • Request based
Production Tips And Tricks Reliable session state • Session State can now be external from ASP.NET Worker Process • ASPState Windows NT Service • SQL Server™ • Big reliability wins • Session state survives crashes/restarts • Enables Web farm deployment • Multiple FE machines point to a common state store
Production Tips And Tricks External session state steps • Start ASP State Service on a machine • net start aspnet_state • Create “web.config” file in app vroot, and point it at state service machine: <configuration> <system.web> <sessionState mode=“StateServer” stateConnectionString=“tcpip=server:port” /> </system.web> </configuration>
Session Summary • Very easy to implement • Little or no coding required for most • Enhances the reliability of your apps
For More Information… • MSDN Web site at • msdn.microsoft.com • ASP.NET Quickstart at • http://www.asp.net • 900+ samples that can be run online • ASP.NET discussion lists • For good “best practice” reference applications, please visit IBuySpy • http://www.IBuySpy.com
MS PressEssential Resources for Developers Find out other titles from MS Press books at www.microsoft.com/mspress Choose from Windows 2000, SQL Server 2000, Exchange 2000, Office 2000, .NET Framework, C#, VB.NET, ASP.NET, and XML
TrainingTraining Resources for IT Professionals • Introduction to ASP.NET • Course # 2063 • Available: Now To locate a training provider for this course, please access mcspreferral.microsoft.com/default.asp Microsoft Certified Technical Education Centers (CTECs) are Microsoft’s premier partners for training services
MSDNEssential Resources for Developers Subscription Services Library, Professional, Universal Delivered via CD-ROM, DVD, Web OnlineInformation MSDN Online, MSDN Flash Training & Events MSDN Training, Tech-Ed, PDC, Developer Days, MSDN/Onsite Events Print Publications MSDN Magazine MSDN News MembershipPrograms MSDN User Groups
Where Can I Get MSDN? • Visit MSDN Online atmsdn.microsoft.com • Register for the MSDN Flash Email Newsletter at msdn.microsoft.com/flash • Become an MSDN CD Subscriber at msdn.microsoft.com/subscriptions • MSDN online seminars msdn.microsoft.com/training/seminars • Attend More MSDN Events
Become A Microsoft Certified Solution Developer • What Is MCSD? • Premium certification for professionals who design and develop custom business solutions • How Do I attain MCSD Certification? • It requires passing four exams to prove competency with Microsoft solution architecture, desktop applications, distributed application development, and development tools • Where Do I Get More Information? • For more information about certification requirements, exams, and training options, visit www.microsoft.com/mcp
Visual Studio .NET 2002 J#, Devices Microsoft Developer RoadmapProducts, Technologies, Subscriptions Visual Studio 6.0 VS.NET 2003 • Base features for XML Web services & mobile app development • Client, Server & Services enhancements • Deep integration of solution orchestration • Continued language innovation • Enterprise lifecycle tools • Development teams • Design XML Web services • Provide architectural guidance to teams SOAP Toolkit 2.0 • New product line now maps to all levels of Visual Studio .NET 2003 2002 2001
MSDN Subscriptions Universal Enterprise NEW Professional Operating Systems Library MSDN For Everyone Visual Studio .NET Enterprise Architect Enterprise Developer Professional VB, C++, C# Standard