ASP.NET Developer's Cookbook

  "Okay, I'm biased because I know and like these guys. However, this is a book that I'm going to keep nearby when I write ASP.NET code. They've used their solid experience in the ASP.NET community to write on topics that everyone wants to know about. Don't struggle any more - buy it! "
Ken Cox

Chapter 1: Web Form Basics

The most basic part of an ASP.NET application is the ASPX page, or Web Form. With ASP.NET, Microsoft has opened up the possibility of using compiled, event-driven, object-oriented methods for building dynamic web applications. The Web Form differs from the typical legacy ASP script page in its design and function. Rather than executing top-down as an interpreted script, the Web Form is similar to a VB Form-based application, in that each control raises events that are then wired to particular activities. In this chapter, you will see how to create a Web Form, and how to perform some fairly simple but commonly needed tasks. You will learn more complicated recipes for enhancing your ASP.NET applications and Web Forms in later chapters.

Chapter 2: User Controls

A great way to encapsulate functionality so that it can be used on multiple web forms in an application is with User Controls. User Controls offer a programming model that closely models that of Web Forms, making them very easy for ASP.NET developers to pick up once they are familiar with building Web Forms. The most frequent use for User Controls is to create navigation and other layout elements for an application that can be reused across many Web Forms. They have full support for properties and events, they can be built and deployed using just a text editor, and they can be built with separate HTML and code sections, unlike other Custom Controls. One key limitation of User Controls, however, is that they cannot be referenced outside of their application domain for security reasons. If you need to span multiple applications, you will probably want to use a Custom Control instead.

In this chapter, you will learn the most common tasks that are encountered when working with User Controls. We'll start with the basics, and work up to some advanced recipes that can be used to build totally dynamic websites like Microsoft's IBuySpy Portal.

Chapter 3: Custom Controls

One of the most powerful features of ASP.NET is its support for custom server controls and components. ASP.NET ships with dozens of built-in controls, and developers can easily extend these controls or write their own controls from scratch. Server controls can be used to encapsulate complex user interface logic or business rules, and can benefit from design time support like drag-and-drop and toolbox support and property builders. Custom controls pick up where user controls leave off, providing greater flexibility, reusability, and a better design time experience, but with some added complexity. In this chapter you will find recipes covering some of the most common server control techniques.

Custom controls as a rule inherit either directly or indirectly from the System.Web.UI.Control base class. Controls which are visible on a page should inherit either directly or indirectly from System.Web.UI.WebControls.WebControl, which provides properties like Style that can be used to control the look of the control on the page. Custom controls can be built in a number of ways. Some simply override the Render() method, which controls the HTML that is output in place of the control at runtime. Others act as containers for other controls, and are known as composite controls. Others inherit from existing fully functional controls to create more specific versions of these controls or to enhance their functionality. Controls in ASP.NET can support DataBinding as well as Templates. In fact, there is easily enough information about building controls to fill an entire book (and in fact such a book exists - see below), so this chapter will attempt to cover the most common techniques that you will use, while leaving much of the theory to other books dedicated to control building.

Chapter 4: Caching

Caching can provide huge performance benefits to almost any web application if it is used correctly. The caching support in ASP.NET is top-notch and provides users with the perfect combination of simple one-line page level caching and a powerful and flexible caching API allowing for tight control over how and when data should be cached. In this chapter, you will learn how to use caching on pages, user controls, and in your code to improve the performance of your ASP.NET applications.

Chapter 5: Mobile Controls

In addition to standard web controls, ASP.NET also provides a suite of controls for working with mobile devices. While these control will render in an ordinary PC's browser, their behavior is customized to work with the small form factor of most PDA and Internet-enabled cellular phone devices. In this chapter, you will find several of the most common tasks that face a mobile forms developer.

Chapter 6: ASP.NET Application Configuration

ASP.NET moves away from the registry and IIS metabase settings that were the methods of configuring ASP applications, instead placing most of the setup information into *.config files. Among other things, this allows applications in most cases to be deployed simply by copying all of the files from one location to another. Each server has a machine.config configuration that serves as the default for all applications on that server, and each ASP.NET application can define one or more web.config files to customize these settings for that application. This chapter covers the most common configurations sections you will need for your ASP.NET applications. Remember that these files are all in XML format, which means that they must be well-formed and that they are case-sensitive.

Chapter 7: State Management

ASP.NET provides many different ways to maintain state, or information about a user and their activity on the site, between and within requests. Some of these techniques can be used to persist information about a user for months or years, while others can be used to hold data simply between postbacks as the user interacts with a web form. In this chapter, you will find recipes for maintaining state information in the Application, Session, and ViewState collections, as well as how to store information in browser cookies

Chapter 8: Security

ASP.NET provides support for several different authentication mechanisms, which are set up in the web.config file. These settings allow you to specify which users or which roles should have access to various web forms and other resources in your application. Note that these security settings only apply to files that the ASP.NET engine is set up to handle in IIS, so by default things like .xml, .htm, and .gif are not covered by the ASP.NET security policies. In this chapter you will find recipes that describe how to configure ASP.NET security using several different options, as well as how to properly construct login and logout features for your application.

Chapter 9: Debugging and Error Handling

I would love to be able to tell you that ASP.NET doesn't break, have bugs, or crash, but unfortunately sometimes it does. Usually, at least when I'm the one writing the code, it's the programmer's fault. At times like these, the debugging and error handling features of ASP.NET make my job much easier. In this chapter, you'll learn how to debug your ASP.NET pages, handle errors gracefully without showing them to your end users, and log problem details for later analysis. I hope you never need to use any of these techniques in your application, but I'm pretty sure you'll find at least a few of these recipes useful.

Chapter 10: Basic Data Operations with ADO.NET

ADO.NET provides a huge upgrade from ADO, while maintaining many of the same objects to allow ADO users a relatively painless transition. In this chapter, some of the simpler ADO.NET operations are described, including how to open a connection to several different kinds of data sources, how to use Microsoft's Data Access Application Block, which provides helper functions for accessing Sql Server data. Calling stored procedures using a few different techniques, and using Access Query objects, which are quite similar, are described here as well. Although quite powerful, the syntax required for working with databases can still be quite verbose and tedious to remember, so hopefully this chapter will provide a useful reference to you when you find that you need to perform some common data-related task and can't quite remember the exact code to do it.

Chapter 11: Working with DataReaders and DataSets

In ADO, the Recordset object could represent a collection of in-memory data, like an advanced array, or it could represent a single row of data from a data source, with an open connection to that source to navigate and fetch more data. This dual-nature of the Recordset led to some confusion and many bugs, or at least poor practices, when developers treated a Recordset as if it were connected when in fact it was not (and vice versa). To combat this, ADO.NET separates its two primary data retrieval objects into the always-connected DataReader and the never-connected DataSet. The DataReader provides a "firehose" of data -- fast, forward-only, read-only. It is usually the fastest way to access data and uses up very few resources on the server, since only one row of data needs to be held in memory at any given time. However, the disadvantage is that the DataReader holds open a connection to the data source as long as it is in use, so care must be taken to open the DataReader as late as possible and close it as soon as possible once you are finished with it. Proper error handling is a must for DataReaders to avoid resource leaks.

DataSets are disconnected recordsets from the ADO world, on steroids. Unlike recordsets, DataSets can hold multiple tables' worth of data. In addition, the DataSet can specify the types and constraints and keys of those tables, as well as their relationships to one another. In concert with the DataView, this data can be queried and sorted and filtered in a variety of ways. Essentially, each instance of a DataSet is a full-fledged database, kept in memory. Unlike DataReaders, DataSets can be serialized, which means they can be passed to and from web services, and cached. In this chapter you will find recipes that demonstrate most of the commonly used functionality if DataSets.

Chapter 12: XML

Extensible Markup Language, XML, has been a great success as a standard and is now found throughout the information industry on all major platforms. Microsoft has throroughly embraced XML, and has provided a great deal of support for it in the .NET Framework. In fact, I'm composing this chapter within an XML document, which I am editing with Visual Studio .NET. We have already seen in chapter 6 that ASP.NET configuration files are all XML formatted. In this chapter, you will learn how to open, read, manipulate, transform, and save XML data. The System.Xml namespace holds all of the releavant classes that you will use to work with XML data, and the most commonly used ones are covered in this chapter.

Chapter 13: Rendering Data with ASP.NET WebControls

ASP.NET provides several web controls that make displaying data on a web page easier than every before. In this chapter, you will see how to take advantage of a process called DataBinding to easily display data in a variety of formats using very little code. This chapter will cover many of the most commonly used features of the Repeater, DataList, and DataGrid, including some fairly advanced DataGrid features. Using these databound web controls, it is very easy to write data driven web forms by just dragging and dropping a few controls onto a form and writing a few lines of code.

Chapter 14: Working with Classes

Unlike ASP, ASP.NET's languages are full-fledged object-oriented compiled languages, not just scripting languages. Thus, as an ASP.NET developer, it is important that you be familiar with object oriented programming features like classes, inheritance, methods, properties, and events. This chapter is by no means meant to provide a foundation in OOP, but it does demonstrate the syntax used for many of the more common features related to classes, which make up the foundation for all object oriented programs. Although these features are not directly related to programming ASP.NET web forms, you will that as an ASP.NET developer you will find that these features of classes become especially useful as you write more advanced and reusable applications.

Chapter 15: Manipulating Strings

Strings of text make up the primary content of almost any web page, and so understanding how to work with this data type is critical for any web developer. This chapter covers many of the techniques available in the .NET Framework for manipulating string data, and while it is not specifically part of ASP.NET, it is definitely something that ASP.NET developers need to understand. Most of these techniques are very simple to implement once you know which method to call or which framework class to use, and it is primarily this latter knowledge that you will gain by referring to the recipes in this chapter when you find yourself needing to perform some string manipulation.

Chapter 16: Working with Numbers, Dates, and Times

One of the most common sources of questions in online forums and communities like involves working with and formatting numbers, dates, and times. Naturally most non-trivial applications require some code to access, modify, or present numeric and/or datetime data, so it makes sense that this common requirement is a frequent source of confusion. In this recipe, you will find recipes describing how to perform many of the most common operations on numbers, dates, and times using the .NET Framework. Although presented in VB.NET, wherever possible the .NET routines used in this chapter are available to C# and any other .NET language, and are not VB-specific.

Chapter 17: Working with Files and Folders

Working with file system resources is a very common requirement in web-based applications, which is why we have included a chapter devoted to common file and folder operations in this ASP.NET book. In this chapter, you will find recipes describing how to find, open, delete, copy, move, read, write, and otherwise work with files and folders using the .NET Framework's System.IO namespace libraries. For most of these operations, you will need to ensure that the ASPNET worker process has sufficient permissions, or that the user is logged in with an account that has the necessary permissions.

Chapter 18: Working with Collections

Collections play an integral part in any non-trivial application, whether they be simple arrays or more complicated data types. The .NET Framework provides a namespace, System.Collections, full of ready-to-use collections of various flavors. In this chapter, you will find recipes that demonstrate the use of the most common of these built-in collections, as well as examples of how to write your own collections. Once you have that mastered, you'll want to look at some of the references provided, which link to automatic collection code generators that can greatly reduce the amount of grunt work you must go through.

Chapter 19: Web Services

Web services have received a great deal of press in recent years, and they certainly are useful in many situations. With the .NET Framework, Microsoft has made it incredibly easy to expose and consume web services in your ASP.NET applications. In this short chapter, you will find everything you need to begin using web services in your applications.

Chapter 20: LDAP/ADSI Directory Services

Directory stores are becoming an increasingly common piece of enterprise applications. Active Directory is just one such directory store, and the Lightweight Directory Access Protocol (LDAP) provides access to many others. The .NET Framework's support for directory store access is mainly contained within the System.DirectoryServices namespace. This chapter's recipes demonstrate the most common operations you will need to perform using the classes contained in this namespace.

Chapter 21: Internet Tasks and Techniques

Many web applications require specific network resources to perform their function. Uploading files, sending or retrieving email, and making HTTP requests are some of the most common Internet tasks that web applications must perform. In this chapter, you will find a variety of recipes describing how you can utilize standard Internet protocols in your applications with the help of the .NET Framework's class library.

Chapter 22: Generating and Manipulating Images

The .NET Framework class library includes an API for working with images, called GDI+. The classes that comprise GDI+ are mainly found in the System.Imaging namespace. This graphics library can be very useful within web applications, allowing dynamic manipulation or generation of charts, buttons, drawings, and images. In this chapter, you will find recipes covering many of these techniques.

Chapter 23: Threading, Reflection, and CodeDOM

To wrap up, a few of the more advanced topics have been included in this final chapter. As you've no doubt realized, the .NET Framework provides a huge amount of built-in functionality. In this chapter, you will find recipes that demonstrate the framework's support for threading, reflection, remoting, and CodeDOM (Code Document Object Model). Although you most likely won't use these recipes every day, they're definitely good to have on hand when the need arises.