What This Book Is About

This book is a collection of ASP.NET 2.0 recipes that aims to help you quickly and efficiently solve many of the day-to-day problems you face when developing web applications with the .NET platform. Our recipes run the gamut from simple coding techniques to more comprehensive development strategies that the most experienced ASP.NET programmers will savor. Revised and updated for ASP.NET 2.0, the ASP.NET 2.0 Cookbook is your ultimate ASP.NET 2.0 code sourcebook.

This book is tailored to ASP.NET 2.0. Thus, the vast majority of the code will not run in the ASP.NET 1.x environment. If you're working with ASP.NET 1.x, consider instead O'Reilly's ASP.NET Cookbook (the first edition of this book).

More than a compilation of tips and tricks, the ASP.NET 2.0 Cookbook solves realworld programming problems and is rooted in our experience as professional programmers who have designed and built richly functional web-based projects for various corporate clients. We think we know the kinds of problems that you face, and we aim to help you solve them.

The ASP.NET 2.0 Cookbook contains dozens of code examples, ranging from relatively simple 10-liners to comprehensive, multipage solutions. Without solid and complete working examples, it's difficult to make an informed decision about whether an approach is the right one or whether you should be looking elsewhere. We are convinced that reading good example code is the best path to understanding any development platform, so we've included lots of it and commented our listings to help you follow the logic.

The ASP.NET 2.0 Cookbook is written in classic O'Reilly Cookbook style to focus directly on problems you face today or are likely to face in the future. Using a problem-and-solution format, we make it easy for you to skim for a near match to your particular problem. We have pared down the headings to a bare minimum so you can assess if a recipe is pertinent.

Many of us occasionally browse through cookbooks looking for new recipe ideas or exploring the nuances of a culinary style. Similarly, we hope you find this book sufficiently interesting to browse, because in many respects, it is as much about software techniques and methodology as it is about ASP.NET. For example, we offer a full course of error-handling recipes because we believe the topic is important to our audience and there isn't enough information about it in general circulation. We could have restricted our discussion to page-level error handling, but that seems inadequate to us. Instead, we prefer to help you deal with error handling at the application level, a more difficult subject but ultimately more useful to serious developers. We have done the heavy lifting on this and many other important subjects so that you don't have to.

Code reuse is central among the techniques that serious developers consider important, and we've gone to some lengths to illustrate its application in ASP.NET. For example, Chapter 5 includes a recipe that shows how to reuse a code-behind class with another .aspx file to provide a different user interface. This is done without any additional coding. As another example, Chapter 4 includes a recipe that sets the focus to a specific control when a page is first loaded, something that could have been accomplished by including some JavaScript in the page's HTML. However, we take a different track by programmatically generating JavaScript client-side code. The reason stems from the type of development work we do, where we are constantly under the gun to quickly generate high-quality code, the ultimate in "short-order cooking." Thus, we are constantly looking for ways to reuse code. By creating a forms library, complete with custom classes that can programmatically generate Java-Script, we are able to build custom forms with a few calls to the library. It's an approach that has proven highly successful for us, and we felt it was important to provide you with a glimpse of it. This is just one of many "reuse-oriented" approaches you'll find in this book.

Who This Book Is For

This book is for journeyman programmers who know the basics of ASP.NET. That said, we're confident that if you are a novice ASP.NET programmer, you will find a home here provided you have done some ASP.NET and either VB or C# programming and are willing to invest time in closely studying our code.

Because this book is not a complete reference for ASP.NET 2.0, it is unlikely to appeal to you if you have merely dabbled in ASP.NET up to this point. You will be better served by first reading a general introduction to ASP.NET programming, such as Programming ASP.NET 2.0, by Jesse Liberty and Dan Hurwitz (O'Reilly), where topics are dosed out in measured spoonfuls. After you have mastered the basics, you'll be ready to read this book. We encourage you to look to a general reference or to the MSDN Library when you have routine questions about ASP.NET.

The generous feedback we have received on the first edition of the book tells us that many readers have found the ASP.NET Cookbook to be a great way to learn ASP.NET. Some have even recommended that aspiring ASP.NET developers should read it from cover to cover. We are delighted that some readers have used the book this way, but we anticipate that most will reach for this edition only when they need to solve a development problem, so we have organized it for this purpose. Still, we hope you find, as others have, that after months of such use, the book is looking a bit tattered but your ASP.NET code is looking quite good.

How This Book Is Organized

This book is organized into 21 chapters, each of which focuses on a distinct ASP.NET 2.0 topic area.

Chapter 1, Master Pages

Master pages are designed to help reduce the replication of identical HTML in your application pages, and the recipes in this chapter show how to make the most of them. The first recipe shows you how to create a quick master/content page arrangement to familiarize you with the approach for using master pages. Next, we cover how to extend a master page's content to include content for other application pages, which is useful when you want your application's login page to appear in one style and the pages that follow it to appear another. The third recipe shows you how to change to another master page without having to edit all of the pages in an application, a common scenario when reuse is important to your application. The last recipe describes how to set the master page programmatically, which can be important when you want to change the application's appearance at runtime. Besides showing you some useful techniques for using master pages, these recipes provide the consistent appearance for all the recipes in the book.

Chapter 2, Tabular Data

In its simplest form, displaying tabular data is easy in ASP.NET 2.0: drop in an ASP.NET grid control, connect to the database, and bind it to the control. This is simple enough but it doesn't take long before you realize that the default appearance and behavior of the control is lacking. Indeed, you may even find that the control you've chosen is too bulky, slow, or confusing when it comes to adding to or modifying its behavior. This chapter helps you make a well-informed decision about which control to use and then provides you with some recipes to solve common development problems as you adapt the control to your liking. Special emphasis is given to ASP.NET 2.0's new GridView control, for which we provide several recipes and discussions on the latest ASP.NET 2.0 techniques.

Chapter 3, Validation

This chapter provides recipes that perform a number of data validation tasks, such as ensuring that the data a user enters is within a defined range or conform to a specific data type. Other validation recipes show how to ensure that the data entered by the user matches a specific pattern or an entry in a database. You'll learn how to ensure that the user selects an entry in a drop-down list.

Validation groups are new to ASP.NET 2.0, and the last two recipes in the chapter shows you have to take advantage of them. The first shows the basics, and the second goes into more depth by showing you how to handle the validation under programmatic control, which is useful when you want to perform your own nonstandard validation, such as when you want to check a new user's registration against a database.

Chapter 4, Forms

The solutions in this chapter provide a series of nonobvious solutions for working with forms. For example, rather than requiring that the user always click a Submit button to send the information on a form to the server, you'll learn how to support the Enter key as well. Another recipe shows how to submit a form to a page different from the current page, which is handy when you want, for example, to have one page that collects form data and a second page that processes the data. Still another shows how to create what appears from the user's perspective as a multipage form but which is actually a single page that uses the Wizard control new to 2.0a useful technique when you want to keep all of your code in one cohesive unit. Next, you'll learn how to set the focus to a specific control when a page is first loaded, an easy solution for JavaScript but one that is more complicated (and more useful) when you focus on code reuse. Finally, you'll learn how to set the focus to the first control on your form that has a validation error.

Chapter 5, User Controls

User controls are a way of encapsulating other controls and code into reusable packages. This chapter shows some ways to use these time- and work-savers to share the same header across multiple pages, display a navigation bar that appears customized on each page by setting properties, and reuse identical code-behind classes within different pages while changing the user presentation in the process. Another recipe shows how to communicate between user controls using event delegates, a handy technique, for example, when you want an action taken with one control to affect multiple other controls. The final recipe in this chapter shows how to programmatically load a user control at runtime, which allows you to customize web page content based on a user's selection.

Chapter 6, Custom Controls

The recipes in this chapter center on custom controls, for which you can build your own user interface and add your own backend functionality through the methods, properties, and events that you implement for the controls. For instance, one recipe shows how to combine two or more controls into a single custom control. Another recipe shows how to create a custom control that has HTML-style attributes, which can be handy for customizing the control when it is used in a page. A recipe for creating a custom control maintains state between postbacks, like the server controls in ASP.NET. Another recipe shows how to customize an ASP.NET TextBox server control to allow only numeric input.

Chapter 7, Maintaining State

The recipes in this chapter are all about maintaining state at the application, session, and page levels, all for the purpose of improving the user's experience. For instance, one recipe shows you how to maintain information needed by all users of an application by placing it in the Application object. Another shows how to maintain information about a user throughout a session, the advantage here being that you avoid accessing the database each time the data is needed. Another recipe shows how to preserve small amounts of information on a page between postbacks, which is useful when a page has multiple states and it needs to remember the current state value between postbacks to display properly. Another recipe shows you how to persist complex object information between requests for a page, a useful technique when the page is complex and you don't want to use a database to preserve the information.

Chapter 8, Error Handling

This chapter covers error handling at different levels of detail. For example, one recipe shows how to provide robust error handling in methods by taking the best advantage of .NET structured exception handling for dealing with errors. A page-level error-handling recipe shows you how to trap any error that occurs on a page and then, using a page-level event handler, redirect the user to another page that displays information about the problem. Another recipe shows how to handle errors at the application level to log the error information and perform a redirect to a common error page. The final recipe shows how to log detailed messages for debugging, while displaying friendly messages to the user.

Chapter 9, Security

Security can be handled in different ways and at different levels in ASP.NET, and this chapter provides recipes that delve into some of the most common solutions. For instance, the first two recipes show you how to use Forms authentication to restrict access to all or only some pages of an application. Another recipe shows you how to restrict access to pages by the user's role. One recipe shows you how to use Windows authentication, which is useful when all users have accounts on your LAN. The final recipe in the chapter shows you how to use ASP.NET 2.0's Membership and Role providers to secure your web site without having to write any code.

Chapter 10, Profiles and Themes

ASP.NET 2.0 has a host of new profile features that are this chapter's recipe subjects. The first recipe shows you how to include user profile data in your application without having to write any code to persist it. The second recipe shows you how to inherit a profile, which is useful when you want to use the same profile definition in multiple applications. The next recipe shows you how to store profile information for users who are not logged in to your application and how to create a mechanism to remove user profile data periodically that is no longer being used.

Themes are another important feature that is supported in ASP.NET 2.0. The penultimate recipe in the chapter shows you how to create an ASP.NET 2.0 theme and how to store a selected theme in a profile. The last recipe shows you how to manage user-personalized themes.

Chapter 11, Web Parts

Web parts are the new building blocks of personalization in ASP.NET 2.0, and this chapter will take you a long way down the learning curve in using them in your applications. We start with a recipe that shows you how to use ASP.NET server and user controls as web parts, which is the equivalent of "hello world" for web parts. Creating a reusable web parts catalog is the subject of the next recipe. Creating such a catalog provides you with the ability to have a user control that is a list of controls reused on many pages of an application without having to declare the controls in each page. Creating a custom web part is the subject of the third recipe, which is useful when you need some functionality for your web parts that you cannot get with user controls or standard ASP.NET server controls, such as building your web part into a separate assembly for sharing with other applications. Another recipe shows you how to communicate between web parts, which is handy, for example, when one web part needs to act as a filter for another web part. Persisting personalized web part property settings is the subject of the last recipe in the chapter, which is beneficial when you have created a web part with custom properties and you want the property data to be persisted along with the other web part personalization data, so that they are available the next time a user revisits a page.

Chapter 12, Configuration

The recipes in this chapter deal with how to configure your applications. For instance, one recipe shows you how to change the default HTTP runtime settings in web.config, as a way to familiarize yourself with this file, its contents, and its purpose. Another recipe shows you how to add your own custom application settings to web.config (by adding an <appSettings> element). Still another shows you how to display custom error messages by adding a <customErrors> element to web.config. Configuring your application to maintain session state across multiple web servers is the focus of another recipe; this is useful because it shows you how to share session state across a load-balanced web farm or web garden. Another recipe shows you how to read configuration data from something other than the <appSettings> element of web.config (by using the WebConfigurationManager), a useful technique when you need it but, surprisingly, one that is not covered anywhere in the ASP.NET documentation. The chapter's final recipe covers how to add your own configuration elements to web.config, which is valuable when the predefined configuration elements provided by ASP.NET are not enough.

Chapter 13, Tracing and Debugging

The recipes in this chapter will help you ensure that your applications work as anticipated in their first release, through effective use of testing and debugging. For example, one recipe shows you how to identify the source of page-level problems, such as a slowly performing page. Another shows you how to use tracing to identify application-wide problems without having to modify every page or disrupt output. Still another shows you how to dynamically turn on page tracing to pinpoint the cause of an exception error. Identifying problems within web application components is addressed by another recipe. A follow-up recipe shows you how to identify problems within dual use (non-web-specific) components, which requires a slightly different approach to avoid breaking the component when it is used outside ASP.NET applications. The final few recipes deal with writing trace data to the event log with controllable levels, sending trace data via email with controllable levels, and using a breakpoint to peer into an application when a condition is met.

Chapter 14, Web Services

XML web services are a marquee feature of .NET, and the recipes in this chapter will help you create and consume them. You will find a recipe for creating a web service that returns a custom object, a handy approach when none of the .NET data types meets your needs. Another recipe shows you how to control the URL of a web service at runtime.

Chapter 15, Dynamic Images

When working with a creative design team, you may run into the situation where a design uses images for buttons but the button labels need to be dynamic. A recipe in this chapter will show you how to deal with this situation with aplomb by drawing button images on the fly. Another recipe shows you how to create bar charts on the fly from dynamic data. Displaying images stored in a database is the focus of another recipe, which shows you how to read an image from the database and then stream it to the browser. The final recipe in the chapter shows you how to display a page of images in thumbnail format.

Chapter 16, Caching

ASP.NET provides the ability to cache the output of pages or portions of pages in memory to reduce latency and make your applications more responsive. If pages are completely static, it's a simple decision to cache them. But if the pages change as a function of query string values or are dynamically created from a database, the decision to cache is not so straightforward. The recipes in this chapter will help you sort through these issues. An additional recipe delves into caching pages based on the browser type and version. A follow-up recipe discusses how to cache pages based on your own custom strings, which gives you, for example, the ability to cache a page based on the browser type: the major version (integer portion of the version number) and the minor version (the decimal portion of the version number). You will find a recipe that shows you how to cache pages based on database dependencies, which is important when the data on a page is retrieved from a database. Two additional recipes show you how to cache user controls and application data. The penultimate recipe in the chapter shows you how to cache application data based on database dependencies, and the last recipe deals with how to cache data sources.

Chapter 17, Internationalization

The recipes in this chapter show you the basics of how to internationalize your applications. For instance, the first recipe shows you the necessary web.config settings to inform the browser of the character set to use when rendering the application's pages. Another recipe shows you how to support multiple languages in an application without having to develop multiple versions of pages. The final recipe shows you how to override currency formatting, which can be handy, for example, when you want all the text displayed in the user's language but currency values displayed in a specific format, such as U.S. dollars.

Chapter 18, File Operations

The recipes in this chapter focus on how to download files from and upload files to the web server. One recipe shows you how to process an uploaded file immediately without storing it on the filesystem, which is handy when you want to avoid the potential pitfalls of uploaded files having the same name or filling the hard drive, or when dealing with the security aspects of allowing ASP.NET write privileges on the local filesystem. The final recipe in the chapter shows you how to store the contents of an uploaded file in a database, which is a useful approach when you want to upload a file to the web server but process it later.

Chapter 19, Performance

You will find that performance is a running theme throughout the course of this book. Nevertheless, there are a handful of topics in ASP.NET for which performance warrants seperate discussion. For instance, as discussed in one recipe, you can often reduce a page's size (and improve the page's performance) by disabling the ViewState for the page or for a set of controls on the page. Another recipe deals with the oft-mentioned topic of using a StringBuilder object instead of the classic string concatenation operators (& or +) to accelerate string concatenation. The difference in this recipe is that we give you some tangible measures to help you understand how important this approach is and when you can do without it. Another recipe illustrates how to get the best performance out of your application when you are using read-only data access. Another recipe shows you how to use SQL Server Managed Provider to get the best performance when accessing SQL Server data. Again, we give you some tangible measures, and the results are amazing.

Chapter 20, HTTP Handlers

An HTTP handler is a class that handles requests for a given resource or resource type. For instance, ASP.NET has built-in HTTP handlers that process requests for .aspx, .asmx, .ascx, .cs, .vb, and other file types. This chapter provides recipes for creating your own custom HTTP handler, which is a useful approach anytime you want to handle an HTTP request for a resource on your own. For example, one recipe retrieves image data from a database and sends the image data to a browser. A second recipe shows how to create a file download handler.

Chapter 21, Assorted Tips

This chapter contains a handful of recipes that do not fit conveniently into other chapters of the book. There are recipes for accessing HTTP-specific information in classes, executing external applications, transforming XML to HTML, determining the user's browser type, dynamically creating browser-specific stylesheets, saving and reusing HTML output, and sending mail.

Topics Not Covered

Though the ASP.NET 2.0 Cookbook's coverage is wide-ranging, there are many topics we don't cover. For instance, we won't teach you the basics of XML. (Many other books do a fine job of it, including O'Reilly's XML in a Nutshell.) Rather, we use XML in many examples throughout the book and assume you know the basics. Likewise, we apply a similar standard when discussing the fundamentals of object-oriented development and other base-level programming topics.

In a similar vein, we avoid interesting topics that are useless in solving day-to-day development problems. For example, we omitted Passport authentication. Though interesting, the use of Passport authentication is not widespread. Indeed, we have cast away more ideas than we can name because they seemed somehow "off target" for our audience.

Many .NET-related topics are interesting from a programmer's point of view but are not pertinent to ASP.NET 2.0. For instance, working with the .NET process model is a career topic, but a programmer's ability to control it through ASP.NET 2.0 is limited. As a practical matter, topics of this kind didn't make the cut.

Finally, because our main focus is ASP.NET 2.0, we do not delve into the details of using Visual Studio 2005. For the most part, we assume you know the basics of Visual Studio and will only mention something about how to use Visual Studio when we think it is obscure or pertinent.

Sample Source Code

The full source code for the recipes in this book can be found at Samples are provided in VB.NET and C# along with working versions of all the recipes that involve code. The web site will give you all the details on how to download the source code.

Sample Database, Scripts, and Connection Strings

The database used for all samples is a SQL Server 2000 database. It can be found at

As you browse the different sample programs throughout the book, you will see our preferred method of data access is OLE DB. From our experience of writing applications for corporate clients, we have learned that many projects start out using SQL Server but migrate to other database servers, such as Oracle or DB2, during the life of the project. By using OLE DB for data access, we gain the necessary layer of abstraction to switch database platforms easily when and if we need to, without having to change the underlying source code. Nevertheless, when you know that SQL Server will be your database platform for the long run, you will want to use SQL Provider to improve its performance, and Recipe 19.4 will show you how.

The connection string used in the samples throughout the book is shown next. It designates the server as localhost, the database as ASPNetCookbook2, the database user as ASPNetCookbook_User, and the password for the user as work. You will need to change these parameters to conform to your database installation.

 Provider=SQLOLEDB;Data Source=localhost; Initial Catalog=ASPNetCookbook2; UID=ASPNetCookbook_User; PWD=w0rk" 

Conventions Used in This Book

Throughout this book, we've used the following typographic conventions:


This character style is used for emphasis as well as for online items and email addresses. It also indicates the following elements: commands, file extensions, filenames, directory or folder names, and UNC pathnames.

Constant width

This character style in body text indicates language constructs, such as the names of keywords, constants, variables, attributes, objects, methods, events, controls, and HTML or XML tags.

Constant width bold

This character style is used to call your attention to lines of source code that are especially pertinent in a recipe.

Constant width italic

This character style indicates replaceable variables in examples. When a variable appears in this style it is a signal to you that the variable needs to be replaced by contents of your own choosing.

Indicates a VB code snippet.

Indicates a C# code snippet.

This icon signifies a tip, suggestion, or general note.

This icon indicates a warning or caution.

Using Code Examples

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book doesn't require permission. Selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product's documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: "ASP.NET 2.0 Cookbook, Second Edition, by Michael A. Kittel and Geoffrey T. LeBlond. Copyright 2006 O'Reilly Media, Inc., 0-596-10064-7."

If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at

Comments and Questions

Please address comments and questions concerning this book to the publisher:

O'Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international or local)
(707) 829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at:

To comment or ask technical questions about this book, send email to:

For more information about our books, conferences, Resource Centers, and the O'Reilly Network, see our web site at:

Safari Enabled

When you see a Safari® Enabled icon on the cover of your favorite technology book, that means the book is available online through the O'Reilly Network Safari Bookshelf.

Safari offers a solution that's better than e-books. It's a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at


The authors would like to acknowledge our editors at O'Reilly. First, we remain indebted to Ron Petrusha for giving us the opportunity to write the first edition of this book. We wish to thank John Osborn in recognition of the fact that this edition bears the mark of his extraordinary work on the first edition. For this edition, we would especially like to thank David Clark for making our job so much easier and for his precision and clarity.

We would like to thank our technical editors: Thomas Lewis and Jason Alexander.

We would like to acknowledge the management team at Dominion Digital, Inc., for their ongoing support and their willingness to host the web site for the book.

Finally, we would like to dedicate this book to our children. Michael to Lisa and Julie. Geoff to Claire and Beau.

ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: