5. Development Tips And Tricks
File upload
ASP.NET provides built-in file upload support
Accessible through two APIs:
No posting acceptor required
No third party components required
Request.Files collection
<input type=file> server control
HttpPostedFile Object:
HttpPostedFile.InputStream
HttpPostedFile.ContentType
HttpPostedFile.FileName
HttpPostedFile.SaveAs(fileLocation)
6. 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>
8. 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
10. 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
12. Development Tips And Tricks
ASP.NET XML Server Control
ASP.NET <asp:xml runat=server>
Binding options
Enables output of XML
Enables optional XSL/T transform of XML
File system
Database item
Built-in caching
Ensure efficient re-use
Improves performance
13. Development Tips And Tricks
<ASP:XML> file sample
<html>
<body>
<asp:xml id="MyXml1"
DocumentSource="SalesData.xml"
TransformSource="SalesChart.xsl"
runat=server />
</body>
</html>
15. 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/>
17. 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
18. Development Tips And Tricks
App settings steps
1.
Create “web.config” file in app vroot:
<configuration>
<appSettings>
<add key=“dsn”
value=“localhost;uid=sa;pwd=;Database=foo”/>
</appSettings>
</configuration>
2.
To return value:
Configuration.AppSettings(“dsn”)
20. 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
21. Development Tips And Tricks
Cookieless sessions steps
1.
2.
Create “web.config” file in app vroot
Add following text:
<configuration>
<system.web>
<sessionState cookieless=“true”/>
</system.web>
</configuration>
22. 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
24. 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
25. Error Handling Tips And Tricks
Page tracing steps
1.
Add trace directive at top of page
<%@ Page Trace=“True” %>
2.
Add trace calls throughout page
Trace.Write(“Button Clicked”)
Trace.Warn(“Value: “ + value)
3.
Access page from browser
29. 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
30. 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
32. 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>
33. 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
37. 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 applicationspecific performance data
Great for real-time application monitoring
Example: total orders, orders/sec
39. 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
40. Production Tips And Tricks
Reliable session state
Session State can now be external
from ASP.NET Worker Process
Big reliability wins
ASPState Windows NT Service
SQL Server™
Session state survives crashes/restarts
Enables Web farm deployment
Multiple FE machines point to a common
state store
41. Production Tips And Tricks
External session state steps
1.
Start ASP State Service on a machine
2.
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>
43. 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
44. MSDN For Everyone
MSDN Subscriptions
Enterprise Architect
Universal
Enterprise Developer
Enterprise
Professional
Professional
Operating Systems
VB, C++, C#
Standard
Library
NEW
Visual Studio .NET
45. .NET Developer SIG’S
(CT, MA and ME) msdn.microsoft.com/usergroups
4th Tuesday of each month (CT)
2nd Wed of each month (MA and ME)
MA http://www.nevb.com
BACOM 2nd Monday (MA)
ME http://www.mainebytes.com Feb 21 – ASP.NET Tips and Tricks
MA http://www.idevtech.com
VB.NET 1st Thursday (MA)
CT http://www.ctmsdev.net.
MA http://www.bacom.com
Share Point Server (MA) 4th Tuesday
MA http://www.starit.com/sughome
First meeting Feb 4 – 7pm
46. .NET Developer SIG’S
(NH, VT, RI) msdn.microsoft.com/usergroups
.NET user groups in NH
.NET user group in Burlington VT
http://www.nhdnug.com
http://www.jjssystems.net
First meeting Feb 11 – 6PM – ASP.NET Tips and
tricks
.Net user group for RI
Details coming
47. Do you have a very large shop?
See Russ (rfustino@microsoft.com) or
Bill (wheys@microsoft.com)
about .NET Readiness offer.
A B B ASEA BROWN BOVERI INC
PARTNERS HEALTH CARE INC
AETNA
RAYTHEON COMPANY
CIGNA
STAPLES
CVS
TEXTRON INC
E M C CORPORATION
THOMSON CORPORATION
GETRONICS
TYCO INTERNATIONAL
GILLETTE COMPANY
UNITED HEALTHCARE CORP
INVENSYS PLC
UNITED TECHNOLOGIES
CORPORATION
And more…
NORTHEAST UTILITIES
48. If you’re an ISV….
email Joe Stagner at
NEISV@Microsoft.com and introduce
yourself!
49. .NET Blitz program
For your development staff with a minimum size
of 10 developers in over 300
pre-approved companies.
One day onsite training – (seminar format)
Needs analysis
90 day MSDN Universal for 5 developers
Contact rfustino@microsoft.com to see if your
company is on the list.
50. Live Webcast Events:
http://www.microsoft.com/usa/webcasts/upcoming/
Architecting Web Services
January 14, 2002 , 3pm
Microsoft Webcast Presents: XML Basics January
16, 2002, 3pm
.NET Class Libraries From A to Z
January 22, 2002, 2pm
Understanding Visual Inheritance
Jan 23, 2002 3pm
Advanced Web Services Using ASP .NETJanuary
29, 2002, 2PM
Webservices 101January 30, 2002 3pm
Advanced XML/XSLFebruary 1, 2002 3:30pm
How To Build Mobile Solutions Using the
Microsoft Mobile Internet Toolkit February 5, 2002
2pm
Caching ASP.NET Application Settings February 6,
2002, 3pm
Building a .NET Mobile Solution
February 13, 2002 3pm
51. Live Webcast Events:
http://www.microsoft.com/usa/webcasts/upcoming/
XML and Web Enabling Legacy
Applications Using BizTalk Server
2000 February 19, 2002 2pm
Advanced Webpart Development
February 20, 2002 3pm
How To Develop Asynchronous
Applications with .NET Framework
February 26, 2002 2pm
Introducing .NET Alerts February 27, 2002 3pm
Part 1: Architecting an Application
using the .NET Framework March 5, 2002 2pm
Part 2: Building a .NET Application
March 12, 2002 2pm
ASP .NET - Tips and Tricks
March 19, 2002 2pm
KEY MESSAGE: Introduce Session
SLIDE BUILDS: None
SLIDE SCRIPT: Welcome to the MSDN Field Content session ASP.NET Tips and Tricks. This is a 300-Level session. This session will focus on some of the cool new things that you can do with ASP.NET and hopefully you can incorporate them into your own applications.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Session Topics
SLIDE BUILDS: None
SLIDE SCRIPT: Many of the samples that you’ll see in this session use small code blocks and are really easy to follow, so hopefully you’ll be able to get a good grasp on how easy it is to implement many of these tips. I’ve broken this session down into three main categories of tips and tricks.
We’ll look at development tips and tricks and look at some cool things that you can do with your own applications. Next, we’ll look at error handling tips and tricks. Many developers often question how do I handle this and how do I handle that, so we’ll take a look at error handling. Lastly, we’ll look at production or deployment tips and tricks. We’ll look at monitoring and reliability and what you can do to help ensure a smooth production environment.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Prerequisites
SLIDE BUILDS: None
SLIDE SCRIPT: This is a level 300 session, so it does assume you meet certain prerequisites. This session assumes you are familiar with ASP and have some basic knowledge of ASP.NET.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Introduce First Agenda item
SLIDE BUILDS: None
SLIDE SCRIPT:
So let’s take a look at some development tips and tricks and how you can use them in your current applications.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: File Upload is now built-in to ASP.NET
SLIDE BUILDS: None
SLIDE SCRIPT:
The first thing that we’ll look at is something that many developers have been asking for for years: File Upload. There is now a very simple method of uploading files to your web server using ASP.NET without using the posting acceptor, third party components, or ActiveX controls.
If you’ve never looked at how files are upload to a server before using HTML, there’s a simple tag called Input type = file. When rendered in the browser, this tag produces a browse button and text box for an upload path. When submitted, the server will mime encode and download those bits to the server.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: File Upload is now built-in to ASP.NET
SLIDE BUILDS: None
SLIDE SCRIPT:
What Microsoft is now doing with ASP.NET is that you now have access to those posted bits on the server. As part of the Request object there is a new Files collection very similar to the QueryString collection that will give you access to files that are posted to the server. There is also a new Input Type = File server control that will give you really easy drag and drop abilities to include this functionality.
There a couple of cool things that you can do now with the HTTPPostedFile object. You can actually get access to the raw bits that were uploaded using the InputSteam property. So if you want to do a virus check on the bits or write them to a different store you can do that too. You can also get the content type or mime type using the ContentType property. So, if you upload a Word document the ContentType will say “Application/MS Word” or if you upload an HTML file it will say “Text/HTML”. You can get the file name that was used on the client and lastly you can use the SaveAs method to easily save the posted file to disk on the server.
SLIDE TRANSITION: Let’s take a look at what the code looks like.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Example code for File Upload
SLIDE BUILDS: None
SLIDE SCRIPT:
This is a very simple file upload example. First, you’ll see that there is a form tag. To enable file upload, I need to add an enctype or “encoding type” to the form tag. This tells the browser to treat this form special by not just treating it as standared Uuencoded data, but make this a multipart/form data section. Next, there is a simple server control input ID = UploadFile type = file runat = server and a button server control to submit the form and act as the event handler. Basically, when I submit this form, my event handler will run and using the UploadFile server control, I’ll call the SaveAs method and save the file to disk on the server.
You see that this doesn’t download anything special, that it’s just standard HTML to do file upload.
SLIDE TRANSITION:
So let’s see a simple example.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Introduce Demo for File Upload
SLIDE BUILDS:
SLIDE SCRIPT:
In this demo, you’ll see how to use the new file upload code in ASP.NET.
SLIDE TRANSITION:
Many people have been asking for simple file upload, but there are more complex things that you can do as well with file upload.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Other File Upload options, can store file in SQL
SLIDE BUILDS: None
SLIDE SCRIPT:
We saw how to store a file to disk, but wouldn’t it be cool if we could store a file in a database? Saving to the file system is not the only option.
The next sample that we’ll look at saves a file directly to SQL and the file never has to touch the file system. First, we’ll post the file to the server and then access it as an array of bytes in memory without having to save it to disk. Then, we’ll write it into SQL as a BLOB using the Image data type. We’ll also save the ContentType and ContentLength of the file as well. What that will let me do is provide a simple edit link on another page and give me the option to download the file from the database, essentially creating a mini document management system. When someone clicks Open on the edit page, it’s going to automatically read the BLOB, set the proper content type and automatically download the file to the client without ever having to write anything to disk.
SLIDE TRANSITION:
So let’s see how this works.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Introduce Demo 2 – File Upload and SQL
SLIDE BUILDS:
SLIDE SCRIPT:
OK, let’s take a look at some code on how to upload a document directly into SQL.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Generate Images
SLIDE BUILDS: None
SLIDE SCRIPT:
ASP.NET has some really cool tools built in to dynamically create images. For example, I can take some sales data and dynamically create a GIF to display how my sales force is doing. To generate images, I just need to use the System.Drawing name space. This namespace is built in to .NET and encapsulates everything I need to do to create images.
I can do resizing and overlays on top of existing images. The System.Drawing namespace really knows nothing about ASP.NET. It was developed to be used in many places. You can use it in Windows apps, or console apps. The really cool thing about it is that it can read and write to any standard .NET IO stream. Within the System.IO namespace there are lots of classes that define lots of generic IO activities. The file system implements this, as well as MSMQ, and ASP.NET implements this on top of the Request and Response objects.
SLIDE TRANSITION:
So let’s take a look at how System.Drawing works.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Introduce demo 3 – Image generation
SLIDE BUILDS:
SLIDE SCRIPT:
In this demo, you will learn how to use System.Drawing to dynamically generate a image., save it as a byte array as a GIF all in memory, so
SLIDE TRANSITION:
So far we’ve looked at different content types – files, images, now let’s look at another type of content, XML.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: ASP.NET XML Server Control
SLIDE BUILDS: None
SLIDE SCRIPT:
ASP.NET has an XML server control built in, that allows you to easily integrate and handle XML in your applications. It enables output of XML and enables XSL/T transforms of XML in HTML. You can use this XML server control to include entire pages, or just fragments of pages. So let’s say you have an XSL/T that you want to use for part of the page, you can drop an XML server control on to that part of the page just for that use.
You can use the XML server control directly against files and you can optionally use it directly against a database. You can call a standard SQL Select statement that returns XML and then bind that to the XML server control for display.
SLIDE TRANSITION:
The first sample that we’ll look at is binding to a static XML file and XLS file.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: ASP:XML File Sample
SLIDE BUILDS: None
SLIDE SCRIPT:
In this sample, you see that there is an XML server control. The DocumentSource property is set to an XML document and the TransforSource property is set to the XSL document.
SLIDE TRANSITION:
Let’s look at a quick demo of using a static XML file.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Introduce demo 4 – XML Server Control
SLIDE BUILDS:
SLIDE SCRIPT:
In this demo you will learn how to use the XML server control to dynamically bind XML.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: ASP:XML Data
SLIDE BUILDS: None
SLIDE SCRIPT:
In this example, instead of reading XML from a static file, we’ll get the XML from a SQL database. In this example, we’ll use the Northwinds database.
Here we are just going to select * from products. We can then point the document property of the XML server control at the returned dataset then that will generate the appropriate XML graph.
At no point to I need to write to disk, or convert the XML to a string. I can convert it directly to XML on the fly.
SLIDE TRANSITION:
Let’s take a look at what this looks like in the browser.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Introduce demo 5 – XML Server Control
SLIDE BUILDS:
SLIDE SCRIPT:
In this demo you will learn how to use the XML server control to dynamically bind XML.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Application Settings
SLIDE BUILDS: None
SLIDE SCRIPT:
App Settings is great tip and trick to point out. There are many developers that hard-code things into their applications, such as path locations, database connection strings, and MSMQ locations. It’s easy, it’s simple, but it’s also problematic if not done right. The good news is that ASP.NET makes this very easy to do. No longer do you need to put resource string directly into your code, but now you can put them in one clean place called Web.Config. This is a configuration file that is used to configure an ASP.NET application on the server. Also, there’s a very simple API that you can use to get access to this file. It’s called Configuration.AppSettings.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Steps to create Application Settings
SLIDE BUILDS: None
SLIDE SCRIPT:
This is what the XML config file looks like. You just need to add this file to your applications root. You can add as many settings as you want.
In your code, just call Configuration.AppSettings and pass in the setting that you want returned and it will automatically retrieve the setting for you. The neat thing is that this Web.Config file is cached in memory. So, the first time you read this file it will be read into memory, but then from there on, it’s all in memory, so it’s very fast.
Another great reason to use this file is let’s say your system administrator decides to change the SQL password for your database. By using Web.Config, they don’t need to call you, they can just change the value in the Web.Config file and immediately your code will pick up the differences.
One cool thing is that this can be used outside of ASP.NET. It can be used by any component called from ASP.NET.
SLIDE TRANSITION:
Let’s take a look at a sample of using Web.Config.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Introduce Demo 6 – Application settings
SLIDE BUILDS:
SLIDE SCRIPT:
In this demo, you will learn how to use the Application Settings in your applications.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Session state no longer requires client cookies
SLIDE BUILDS: None
SLIDE SCRIPT:
Many developers out there state that they don’t want to use cookies. People get confused about cookies such as permanent cookies for malicious reasons and things such as session cookies. Session cookies are not really storing any thing personal about the user. They’re just storing a session key to be used to get back to session data stored on the server. This is a big problem today. If a client has cookies disabled, your application could break.
With ASP.NET you can now optionally select to support cookieless sessions. ASP.NET can track the SessionID in the URL instead of storing it as a cookie. ASP.NET does all of this behind the scenes for you by inserting a SessionID directly into the URL.
The great thing is that this doesn’t require any code changes to your application. As long as you have relative links, everything will work.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Session state no longer requires client cookies
SLIDE BUILDS: None
SLIDE SCRIPT:
So how do you add support for Cookieless sessions? It’s very easy. In your web.config file, just add a System.Web node under Configuration. Then add a tag called sessionState with cookieless=true.
When you first hit a page with cookieless sessions, ASP.NET will redirect the browser to a URL with a SessionID inserted into it. On each page request, ASP.NET automatically removes the SessionID and hits the page again. All of this is done for you by ASP.NET behind the scenes. You don’t need to change any of your code to get this to work.
The only requirement for this work is for you to use relative links within your pages. This allows ASP.NET to automatically insert the SessionID into the URL’s.
Performance isn’t a factor with cookieless session either. The performance of cookieless sessions is identical to systems that use cookies that get written to the client. Plus, this is absolutely scalable and can easily run on a web farm.
So are there any security risks to this? There are no security risks as compared to using regular cookies. ASP.NET using an algorithim to generate a custom ID to eliminate any guessing. It is still vulnerable to relay attacks that regular cookies are too. If someone is packet sniffing, they can determine the SessionID from the URL.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Smart navigation eliminates browser flicker
SLIDE BUILDS: None
SLIDE SCRIPT:
Wouldn’t it be great to have all the benefits of client side applications such as smooth scrolling and no screen flicker, but have all of your code running on the server? ASP.NET has added a new featured called Smart Navigation to help with this problem. It doesn’t require any new code changes for it to work. Instead, what you do is at the top of the page directive, you set the SmartNavigation = true. What that will do is when a client that has DHTML script enabled hits the page, on postbacks to that page, ASP.NET detects what the differences are in the page that they have and in what they’re getting. Then the client can intelligently repaint only the portions of the page that have changed. The nice thing is that if you hit this with a non-IE browser or a browser that does not have DHTML script enabled, it will automatically degrade. There’s not a lot of downside to using this. Smart navigation works with IE 5 and above.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Introduce second topic
SLIDE BUILDS: None
SLIDE SCRIPT:
OK, now that we’ve spent some time looking at development tips and tricks, let’s take a look at error handling. There are a lot of tips and tricks built into ASP.NET that will help you with error handling diagnosis as well as error handling recovery.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Page and App tracing now easy to do
SLIDE BUILDS: None
SLIDE SCRIPT:
The first tip has more to do with error diagnosis. Lot’s of developers use Response.Write as their primary debugging mechanism in ASP. ASP.NET now has built in tracing. No longer do we need to use messy Response.Write statements. Now, we can use Trace.Write statements.
These Trace.Write statements are conditionally compiled out depending on whether or not tracing is enabled in your application.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Page tracing
SLIDE BUILDS: None
SLIDE SCRIPT:
To enable tracing you just need to add the Page Trace directive to the top of the page. You can then call the Write and Warn methods to output data.
SLIDE TRANSITION:
Let’s take a look at a demo on tracing.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Introduce Demo 7 – Page tracing
SLIDE BUILDS:
SLIDE SCRIPT:
In this demo, you will see how easy it is to use page tracing in your ASP.NET applications.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Application tracing
SLIDE BUILDS: None
SLIDE SCRIPT:
So, there is a way to set a value at the application level to turn on and turn off page tracing. In the Web.Config file, there is a Trace tag that you can use to globally set this trace value. I can set the number of requests that I want to trace by setting the RequestLimit property.
One thing that people have been asking is if you can have tracing enabled but not show all of the extra data at the bottom of the page. What they want to be able to do is send it to a second window perhaps. The idea is that someone can test the app and I can have all of the trace output saved into a file for later use. ASP.NET can do this. There is a virtual file that is created under your application root called “Trace.axd”. By default, when you hit this page, you can see all of the trace statements from the application.
The browser never sees any of this. It doesn’t even know the trace is enabled.
SLIDE TRANSITION:
Let’s take a look at how application tracing works.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Introduce Demo 8 – Application tracing
SLIDE BUILDS:
SLIDE SCRIPT:
In this demo, you will learn how to use Application Tracing to create a trace file for your application.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Error handling
SLIDE BUILDS: None
SLIDE SCRIPT:
.NET now has unified error handling across all languages and components. The common language runtime provides many great ways to handle exceptions. It’s now possible have a C# component throw an exception and then catch it in a VB component and bubble it up the stack. Errors work entirely the same way - It’s a very clean mechanism. When an error does occur, because we have managed code, we get a lot more information about specifics. Even without having debug symbols, we can figure out what the call stack was. You can know what line it was on without debug symbols, but you are able to know where it was called from, etc. That’s even on generic retail production systems. It makes it a lot easier to diagnose after the fact what failed on your system.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Error handling - Notes
SLIDE BUILDS: None
SLIDE SCRIPT:
You can also now use Try Catch and Throw extensions from all languages. ASP and VB as in the past we were used to On Error Goto statements. You can still use that, but now you can have nested Try Catch blocks within your code. You’ll find that Try Catch blocks are a very clean approach to error handling.
This all has to do with what .NET provides. There are a few specifics that ASP.NET provides. One cool thing is that at the application level, you can receive a notification any time an unhandled error occurs. This provides a single point of logging problems to notify administrators. The second thing that you can do is to take advantage of custom error pages. This is a neat way to configure your app, so instead of showing an ugly stack trace, you can display a more user friendly message.
SLIDE TRANSITION:
Let’s take a look at how we work with Application errors.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Application_Error – Global application event
SLIDE BUILDS: None
SLIDE SCRIPT:
There are two steps here. First, tell me what the error is and help me diagnose it and second don’t let my customer know that an error occurred and hide it from them. Now, inside of your Global.aspx file, you can write an Application_Error event. This is just like Application_Start and Application_End. It will get called any time an unhandled exception occurs and within this event procedure you can get access to the Request object as well as the exception object for the error that occurred. So from here, you can write to a database, send an email, or write to the NT event log. You can do anything that you want.
SLIDE TRANSITION:
Let’s take a look at the code on how to write to the NT event log.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Introduce Demo 9 – NT event log
SLIDE BUILDS:
SLIDE SCRIPT:
In this demo, you will learn how to write to the NT event log from your ASP.NET application.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Send STMP Mail
SLIDE BUILDS: None
SLIDE SCRIPT:
In addition to writing the NT event log, you can also send email to an administrator when an error occurs.
The code here is pretty basic but very useful because it will ping an administrator when an error occurs. You see that we just Dim and instantiate a new MailMessage. Then just set some basic properties and send the message. It’s very straight-forward, but quite powerful too.
SLIDE TRANSITION:
So, we’ve talked about the first part of the problem: Telling an administrator when a problem occurs, now we don’t want to tell the customer that a problem occurred.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Create your own custom errors
SLIDE BUILDS: None
SLIDE SCRIPT:
We don’t want customers to see ugly error messages, instead, we may want to show the user a custom page that says the website is undergoing maintenance, or something to that effect. So, ASP.NET provides a mechanism to do this called custom errors without having to write any code. Custom errors hides the error message for you.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Steps to create custom error pages
SLIDE BUILDS: None
SLIDE SCRIPT:
ASP.NET provides a way to configure inside an XML file a default error redirect whenever an unhandled exception occurs. In this sample code, you can see that whenever an unhandled error occurs, I want to go to the error.htm page.
Also, you can see that I set check status codes, such as 404. In this case, I can show an adminmessage.htm page stating that the page is not found. Additionally, I can check for 403 errors and show a page stating that the user does not have privileges. You can configure based on any of the error status codes that get generated.
You can configure the custom errors to be On, Off, or RemoteOnly. On means everyone sees it. Off means no one sees the custom errors. RemoteOnly means that any off the box will see the custom error page and anyone on the box will see the real stack trace. This is great for testing.
SLIDE TRANSITION:
OK, let’s take a look at a custom errors demo.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Introduce Demo 10 – custom errors
SLIDE BUILDS:
SLIDE SCRIPT:
In this demo, you will learn how to incorporate custom errors into your ASP.NET applications.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE:
SLIDE BUILDS: None
SLIDE SCRIPT:
OK, let’s take a look at the third category which is production tips and tricks. You can also think of this as deployment tips and tricks.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Easy to setup performance counters
SLIDE BUILDS: None
SLIDE SCRIPT:
ASP.NET now provides a lot more diagnostic performance counter information. Specially, you can now set Perf Mon counters on a per application basis. So, you can see the number of errors occurring on a per application basis and the number of requests occurring on a per application basis.
Also, you can write your own custom Perf Mon counters within your application. For example, maybe you want to track orders per second, now you can do this quite easily.
SLIDE TRANSITION:
Let’s take a look at a demo on how to do this.
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Introduce Demo 11 – Performance Counters
SLIDE BUILDS:
SLIDE SCRIPT:
In this demo you will learn how to use performance counters within your ASP.NET application.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Process model recovery
SLIDE BUILDS: None
SLIDE SCRIPT:
All of these tips and tricks are cool, provided your application stays up and that you as an administrator don’t have to intervene with running the application.
ASP.NET really focuses on the reliability and recovery aspect of running applications. Specifically, the automatic handling of crashes and access violations that might occur in your app, automatic handling of memory leaks, and automatic handling of deadlock’s is now built in to ASP.NET.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Process model recovery - Notes
SLIDE BUILDS: None
SLIDE SCRIPT:
For example, let’s say you have small memory leak where every time you hit a page you leak 1 K of memory. ASP.NET will now automatically detect that memory leak and when you hit a certain threshold, the process will be shut down and then automatically restarted. You don’t have to configure anything out of the box for this to work, it’s just built-in.
You can now proactively configure your servers to reset themselves automatically. Many people just reboot their servers once a week because they feel like they get better performance. Now, you can set based on some time or the number of requests when you want to have the services recycled. Rather than rebooting the machine, ASP.NET will proactively cycle the worker process. This is done in such a way that no requests are lost. Basically, all of the requests are migrated to a new worker process and then the old worker process is destroyed. The benefit to this is that you app will be much more reliable.
SLIDE TRANSITION:
So, this sounds great, but what happens to Session state?
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Reliable session state
SLIDE BUILDS: None
SLIDE SCRIPT:
The downside to ASP as it is today is that when the worker process goes down, you lose all session state. With ASP.NET inproc session state is supported, but it also supports two new session state mechanisms. The first is the ASPState store which is a dedicated NT service. The second option is to store it directly into SQL Server.
There are two big wins from these new mechanisms. The first is reliability. We can now survive worker process restarts. The second win is that you can now do web farm session state. The front-end web servers are configured to go against a single state store. Regardless of whatever browser in comes in from, it can get access to the session state. You can bounce from server to server without any problems.
SLIDE TRANSITION:
So how do we do this?
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: create custom perfmon counters
SLIDE BUILDS: None
SLIDE SCRIPT:
The first thing that you need to do to enable external session state is to start the State service on your server. You can simply do this by using a command prompt and enter net start aspnet_state. This will start the ASP State service.
The next thing that you need to do is to edit the Web.Config file and point the sessionState tag at the server using the stateConnectionString property. To use the State Service, you set the mode property to StateServer. By using the State service, your web services can be cycled, and you won’t lose your session state.
For the best reliability you’d probably want to configure a separate server just to act as your State server. Then in your web farm, just point your Web.Config files to this central server and all server will be able to use the State store.
It’s important to note that this feature only works with the Professional or Enterprise editions of ASP.NET.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Summerize the session
SLIDE BUILDS: None
SLIDE SCRIPT:
OK, in this session we have only seen a small sampling of hundreds of cool features you could use when building ASP.NET Web Applications. From all the samples we saw today, all the features can be implemented from all .NET languages, and most require little or no coding..
Be sure to take advantage of these new features. Many of them will make your jobs much easier as developers and administrators. I’d definitely recommend using the error handling tips and tricks. Anything that can make error handling easier and more seemless is always a plus. Remember that most of the tips require no coding.
Lastly, be sure to take advantage of performance counters and external session state. External session state could really make a difference in the reliability of your apps.
SLIDE TRANSITION:
So how do you get more information…
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: For more info
SLIDE BUILDS: None
SLIDE SCRIPT:
As always, be sure to check out the MSDN web site for up to date information and resources at msdn.microsoft.com.
One of the best places on the web to get more information on ASP.NET is the ASP.NET web site at www.asp.net. This is a Microsoft owned site with tons of great information and articles. Plus, there are over 900 samples that can be run online.
ASP.NET discussion lists are another great resource to check out. It’s great to sift through some of the posts because you’ll stumble on to things you would have never thought about before.
I’d also recommend checking out the IBuySpy sample applcation to see some best practices, etc. This is a fully functioning demo application that you can download and run on your server. The database and source code is all included in a simple to use setup program. It only takes about 2 minutes to setup. There are lots of code snippets that you can steal and reuse in your own apps.
SLIDE TRANSITION:
ADDITIONAL INFORMATION FOR PRESENTER: