Chapter 22. Introduction to ASP.NET 2.0 and Web Forms

IN THIS CHAPTER

ASP.NET is a web development framework that provides developers with an advanced, object-oriented interface to the creation and manipulation of HTML that will be rendered to the client. More than that, ASP.NET provides a rich event-driven model that resembles the event-driven model that Windows Forms developers are familiar with. This chapter provides you with an introduction to ASP.NET and a list of the controls and tools that will be available to you for creating compelling web applications using ASP.NET. In addition, this chapter contains a guide to creating and debugging your web applications, handling server-side events in your code, and even a look at how to use one of the powerful new ASP.NET 2.0 features: client callbacks.

Introduction to ASP.NET 2.0

Prior to the first release of ASP.NET, the tools available to developers for creating powerful and compelling web applications were limited and immature.

One of the first widespread tools for creating web applications was the CGI (Common Gateway Interface) standard, which essentially allowed a customized console application to run when invoked from the web and return a stream of text to the end user that served as an HTML page.

A tool that helped make web development commonplace was Active Server Pages (ASP). ASP is a framework that allows developers to embed scripting language (VBScript or JavaScript) code directly in their web pages, drastically increasing the time to market for many applications, especially data-driven web applications.

When the first version of the .NET Framework was released, it was released with ASP.NET. ASP.NET is a framework that takes the concept introduced by classic ASP to a new level. It allows you to write managed, compiled, secure, and reliable code to drive your web application, as well as providing a hefty library of code that automates standard web application tasks such as security, authentication, authorization, membership, and much more.

ASP.NET works by compiling the content in your web application into an assembly that is then used by Internet Information Server (IIS) to service requests for pages and web services. The ASP.NET Framework is made up of several components, including a page and control hierarchy, the page and control compiler, security management, state management, and application configuration. Each of those components is discussed in this section.

Don’t worry if some of the information presented in the sections seems a little vague. As you progress through the ASP.NET chapters of this book, each of the items discussed here will be discussed in more detail with plenty of code samples and practical applications.

Page and Control Hierarchy

Tools such as Active Server Pages (ASP) worked by allowing the developer to write script that output text to a web page. This could become extremely tedious, and reading and maintaining code like that could become burdensome.

ASP.NET provides an entirely object-oriented approach to creating web pages and applications. There are classes that represent pages, applications, user controls, server controls, and much more. By allowing controls to become first-class objects, it becomes much easier to create powerful, reusable visual elements that can be reused among multiple pages or applications. Object inheritance can be used to create entire hierarchies of controls with expanding functionality.

ASP.NET 2.0 provides additional features that allow your applications to support skins and themes for enhancing an application’s look and feel. Another feature new to ASP.NET 2.0 is the concept of master pages, which allow for a kind of visual inheritance among pages, further enhancing the code reuse that is already available in ASP.NET.

Introduction to the ASP.NET 2.0 Compiler

Unlike the original versions of ASP, which were driven by scripting languages such as VBScript and JavaScript, ASP.NET is a completely compiled environment. This means that you can create web applications that not only have strong typing, but can catch a myriad of potential problems at compile time and design time. Loosely typed, scripted environments lend themselves to an aggravating scenario in which problems are difficult to find until the program is being tested at runtime under adverse conditions.

The ASP.NET 2.0 compiler makes use of partial classes to merge the ASP.NET markup found in .aspx and .ascx files with the code contained in associated C# files to produce a compiled assembly.

Each ASP.NET page has basically two halves: the half contained in a .aspx file that contains HTML markup and ASP.NET server controls, and the other half, which contains the remainder of the code. With partial classes, each ASP.NET page produces a single class, even though it is made up of at least two files.

Finally, another major benefit of having fully managed and compiled ASP.NET pages is that each ASP.NET page or control that you create has access to all the same functionality that any other managed application has, and it has that access in a tightly bound fashion. Classic ASP generally required late binding to make use of external components, and those components had to be COM-based.

Security

Above and beyond Code Access Security features that are an inherent part of any managed code application, ASP.NET 2.0 provides a powerful suite of tools and features that help developers create secure applications. ASP.NET has built-in features that manage user authentication using cookies, specially written URLs, Windows authentication, and even support for Microsoft Passport.

Additional providers, tools, and controls are also available that assist in managing user membership on your site, user security roles, and much more.

State Management

HTTP is what is known as a stateless protocol. This means that the protocol itself has no support for maintaining state between multiple requests for a page. HTTP on its own can’t provide the facilities required to maintain state information on a web application such as shopping carts, control state persisting between subsequent requests for the same page, or even simple things such as the current user’s name.

ASP.NET provides facilities for maintaining state that HTTP itself can’t provide. There are facilities for managing session state, which is a temporary store of information that persists for a specific user as long as that user is actively using the application. ASP.NET can manage session state directly within the application process, or it can maintain distributed session state to allow your application to share session state among the multiple servers within a Web Farm. In addition to session state, each ASP.NET control can persist its own state between subsequent requests for the same page through a mechanism called ViewState. ViewState essentially replaces the old technique of using hidden form variables to persist control state information between page requests. It stores information such as a control’s items, width, height, state, and more in a specialized string that stores name/value pairs.

The Web Configuration System

The .NET Framework contains built-in functionality that supports the use of application configuration files. These files are XML files that contain information about .NET configuration as well as application-specific configuration.

ASP.NET extends the default .NET Framework configuration files to include several new sections that control web application configuration. By modifying the XML in these configuration files, you can control the authentication and authorization settings for your application, as well as error handling, tracing, debugging, and much more. The use of these configuration files makes deployment a much easier task. You can store connection strings in a configuration file, and then have a different configuration file for each of your build, stage, and production environments. Without such configuration files, managing multiple instances of the same application without writing a lot of unnecessary code would be extremely difficult.

Understanding the ASP.NET Page Life Cycle

The process by which an ASP.NET page is rendered to the browser consists of multiple stages. These stages all have a very distinct purpose in the creation and rendering of your page. A common problem among new ASP.NET developers is injecting code into the wrong stage in the page’s life cycle. If you put code in the wrong place, controls that you expect to exist might not exist, or the controls might exist but their state might be nonexistent or unpredictable. This section gives you an introduction to the process that ASP.NET uses to render pages. Understanding this process is absolutely crucial to continuing with more advanced aspects of ASP.NET, such as creating and using your own custom controls.

Stages of ASP.NET Page Rendering

To support the object-oriented framework, the event-driven model, and the capability to persist control state between page requests, ASP.NET has several distinct stages in the life cycle of a page. One key concept to remember is that no matter what, a page will be instantiated and destroyed during the same request. The sequence of stages and events in the life cycle is what allows a page to create a control hierarchy, reconstitute itself from persisted ViewState, render its output, and clean up temporary resources used by the page.

Table 22.1 provides you with the list of stages that occur in the lifetime of an ASP.NET page. It is extremely important to understand these stages before you start creating your own ASP.NET applications.

Table 22.1 ASP.NET Page Life Cycle Stages

Image

ASP.NET Page Life Cycle Events

Most of the stages described in Table 22.1 correspond to events that can be handled by your own code. Handling these events allows you to control when your code is executed by placing the code in specific stages of the page’s life cycle. Controls that were supplied with ASP.NET, written by you, or provided by a third party are engaged in the life-cycle stages by having their own miniature versions of the Page life cycle. The Page involves the control in the appropriate stage of the life cycle by triggering control events.

Table 22.2 contains a list of Page events, their descriptions, and typical uses.

Table 22.2 Page Life Cycle Events

Image

To further illustrate the page life-cycle events, the code in Listing 22.1 shows you how to create a page that prints some text to the rendered output during each of the crucial life-cycle events. There is a button on the page so that you can click it and see where its event handler appears in the life cycle, as well as see the use of the IsPostback property.

To create this code, open up Visual Studio 2005 and choose File, New, Web Site. Make sure it’s a standard C# website and not a starter kit or web service. Drag a single button from the Toolbox onto the form. Double-click it to create an event handler. Switch to the code view and override the many OnXxxx() methods that are already configured as event handlers for the events described in Table 22.2. Your default.aspx.cs file should look very similar to the one in Listing 22.1.

Listing 22.1 Default.aspx.cs

Image

Image

When you run this application for the first time, you see the output shown in Figure 22.1.

Figure 22.1 Page life-cycle event demonstration.

Image

After you click the test button, the output now includes information from the event handler created for the submit button, as shown in Figure 22.2.

As you learn more about control building and you work more with ASP.NET pages, the purpose of the events discussed in this section will become clearer to you.

A fairly new concept, the postback, was introduced in Listing 22.1. ASP.NET outputs a JavaScript library that contains many helper functions. One of those functions causes the page to “‘post back”’ on itself. This function places information in the page’s view state that indicates which button was clicked (or which control caused the postback). When the Page life cycle gets to the control event stage, it compares the event that triggered the postback with the event handlers contained in the page, and invokes the appropriate event. In the case of the code in Listing 22.1, the btnSubmit_Click handler was called. The combination of the Page life cycle, postbacks, and some relatively hidden plumbing allows ASP.NET to present the developer with an event-driven model that closely resembles the event-driven model with which Windows developers are very familiar.

Figure 22.2 Page life-cycle event demonstration, after clicking the button.

Image

Overview of Controls Provided by ASP.NET

Before creating something new with wood and nails, a carpenter needs to be familiar with the tools at hand. The same is true for working with ASP.NET. Before looking at any more code samples, you should be familiar with the tools that are available to help you create extremely powerful web applications. These tools come in the form of ASP.NET controls that ship with version 2.0 of the .NET Framework. These controls are all briefly described in Table 22.3 according to the category in which they appear on the ASP.NET 2005 Toolbox pane. The Web Part controls are not included in this table, as they will be covered in much more detail in Chapter 26, “Introduction to Web Parts.”

Table 22.3 Stock ASP.NET Controls

Image

Image

Image

Image

Creating and Debugging ASP.NET Applications

The process of creating, debugging, and deploying ASP.NET applications is slightly different than the process for building and deploying Windows Forms applications. This section familiarizes you with the tools and techniques involved in building, deploying, and debugging ASP.NET applications.

Building and Deploying ASP.NET Applications

The first step toward creating an ASP.NET application is the creation of a new website from within Visual Studio 2005. When you create a new website, Visual Studio prompts you for the location of the site. You can store the website on the file system, on a remote server via HTTP, or on a remote server via FTP. This is a new feature that previous versions of Visual Studio did not support. Prior to ASP.NET 2.0, you couldn’t create web applications without having a copy of IIS on your development server. This new model allows you to create web applications that can be hosted by Visual Studio 2005’s own custom local web server without the need for an IIS installation.

Deploying your web applications after they’ve been created has also become a lot easier in Visual Studio 2005. If you click the Website top-level menu item and then click Copy Web Site, you will see the website copy screen shown in Figure 22.3.

What you can see from the figure is that you can deploy your website to any location, whether it’s accessible via HTTP, FTP, or the file system (so long as you have the appropriate credentials for the destination location). This gives you incredible flexibility in allowing you to deploy your website to development, staging, and production servers all directly from your own workstation within Visual Studio 2005.

ASP.NET applications compile within Visual Studio in the same manner as other applications. The main difference is that the partial class technology creates classes that are combined from the contents of the .aspx files, .ascx files, and so on, and compiles all of those into an assembly used by ASP.NET to service page requests. You will be able to see compile-time errors such as type mismatches, syntax errors, and many more that you would never be able to see in interpreted scripting environments, such as legacy ASP using VBScript or JavaScript.

Figure 22.3 Website copy screen.

Image

Debugging ASP.NET Applications

You can debug your ASP.NET applications from within Visual Studio 2005, including the ability to stop on breakpoints, step through individual lines of code, and make use of the Immediate window. The only real concern is that if you are debugging code on a remote server via HTTP, that server needs to be configured to allow remote debugging.

To experiment with debugging an ASP.NET application, start up the application created in Listing 22.1 and insert a few breakpoints wherever you like. Then, run the application in debug mode (F5), and you will see that even though you’re working with a web application, the code will still stop on the breakpoints, and you still have access to all of the features of the runtime debugger from within Visual Studio.

Two classes facilitate logging trace and debug messages from within an ASP.NET application. The first is the System.Diagnostics.Debug class, which allows you to write simple information to the debug window. The second, which is specific to ASP.NET, is the System.Web.TraceContext class. This class is provided in the Trace property of every page and allows you to output debug information to the ASP.NET trace. Using an ASP.NET configuration file, you can have that trace information automatically displayed at the bottom of a page’s rendered output or in the output of a special page called trace.vxd.

The following are a few lines of code that show how to use these two classes from within an ASP.NET page:

Trace.Write("Debug information");
Trace.Write("Diagnostics", "Event X took 10 seconds.");
Trace.Warn("Something bad happened.");
System.Diagnostics.Debug.WriteLine("Debug information");

Handling Events and Postbacks

Listing 22.1 gave you a brief look at handling server-side events through ASP.NET pages with a submit button. To illustrate how code typically utilizes both the IsPostback property of the page as well as multiple event handlers per form, Listing 22.2 shows you the ASPX code for a page that presents the user with a simple survey, accepts two different button clicks, and presents the user with results. Listing 22.3 contains the C# code for the event handlers in the partial class.

Listing 22.2 Handling Multiple Events, ASPX Code

Image

Image

The page in Listing 22.2 has two panels: one panel for input, and one panel for displaying the results. The idea is to hide the input panel during the postback while revealing the results panel. When the page is first displayed, just the input panel is displayed because the results panel has no controls in the placeholder.

Listing 22.3 Handling Multiple Events, C# Code

Image

Image

When you run the code in the preceding listings, you will be presented with an input form. You can either fill it out and click Submit, which will show you the information you entered (remember that information is reconstructed from view state during the Initialize stage of the page life cycle), or you can click Cancel and be informed that the results of the survey weren’t saved. This provides a good example of where it is appropriate to check for IsPostback and when to perform tasks specific to an individual event.

Building Interactive Dynamic Pages Using Client Callbacks

If you have experience creating full-featured web applications using previous versions of ASP.NET, you have probably run across performance problems involving postbacks. The downside to using server-side events is that in order to trigger such an event, the page must completely reload itself, restore control and page state, and then render according to the new state.

Imagine that you were to create a page where you had three list boxes, and each time you click a list box, the subsequent list box populates with a list of child rows. This is a pretty common pattern, seen in applications where you select a country, then a state, then a city. It is also seen where you select increasing levels of detail from most to least general, such as selecting a company, then a location, then an office. Using purely server-side events, the entire page has to post back and potentially reload all of its data every time the user clicks a list box. This means that to get to the point where the user can proceed, he has clicked three times and caused two potentially slow postbacks.

One solution a lot of developers used in the past was to query all of the data on the first load and then render that data in the form of JavaScript client-side data structures. Then, each time the user clicked a list box, JavaScript would be used to populate the detail lists. This approach yields a pretty fast and reactive web page, but the initial load time becomes horrendous because the browser has to load and parse through mountains of JavaScript data initialization statements. The page size grows exponentially with the amount of data driving the page. This approach creates unwieldy server code and can often be slower than the purely server-side pattern.

The solution to this problem is an incredibly powerful mechanism that essentially allows JavaScript to invoke server-side methods on your page and then receive a response through a callback method that is also written in JavaScript. Callbacks and delegates were covered earlier in the book in Chapter 9, “Events and Delegates.” This tool is referred to as a client callback, and ASP.NET 2.0 supports this functionality by default. Other tools created by third parties are also available that create similar functionality, such as Ajax .NET.

To allow a control to expose a method to client-side JavaScript, that control needs to implement the ICallbackEventHandler interface. This interface requires two methods:

  • void RaiseCallbackEvent(string eventArgument)—This method is, through code you’ll see shortly, invoked by JavaScript. The string argument is used to pass information to the method from JavaScript, such as the ID of the parent row for which to retrieve child rows.
  • string GetCallbackResult()—This method is used to retrieve the results of the previous call to RaiseCallbackEvent. The results retrieval method is separate from the Callback Event method in order to allow JavaScript to make asynchronous calls in the background.

You can choose to implement this interface at the Page level, or at the Control level. If you choose to implement the interface at the Page level, you will find that you can only support one client callback for the entire page. If this is sufficient, then Page-level implementation is definitely the easiest way to go.

However, if you need to invoke multiple client callback methods (for example, you have more than one control that you want to dynamically populate without using an expensive server postback), you will need to create special controls to implement the ICallbackEventHandler interface.

Listing 22.4 contains the ASPx code that sets up a sample that will have three list boxes. The first list box is populated on the initial page load by the server. The second and third list boxes will be populated dynamically using client callbacks without incurring the overhead of a full server postback.

Listing 22.4 ASPx Containing Three List Boxes

Image

Image

Image

The preceding ASP code should look pretty straightforward. There are three list boxes and a button. There are also two JavaScript functions: CallBackReturnFunction and CallBackReturnFunction2. These are both functions that will be called by the client call-back framework when results have been made available by the server in response to their initial requests. These requests are made by additional JavaScript functions: OnCompanyClick and OnLocationClick. As you will see in Listing 22.5, these functions are generated dynamically using the RegisterClientScriptBlock method.

Listing 22.5 Page Code Corresponding to ASPx Code in Listing 22.4

Image

Image

Image

Don’t worry if this looks a little complex. As you progress through the book, the techniques used here will become second nature to you. Keep this sample handy as you go through the rest of the examples in the ASP.NET section and try to apply the technique of client callbacks to the other techniques you’re learning.

The code in Listing 22.5 essentially indicates that two controls, CompanyEventControl and LocationEventControl, are going to be event handlers for client callbacks. Listing 22.6 contains the source code for both of these classes. Their sole purpose is to take a request indicating a parent row and return a specially serialized string (one that can be easily decomposed by JavaScript) containing the appropriate rows.

Listing 22.6 ICallbackEventHandler Implementations

Image

Image

Image

The code in Listing 22.6 responds to a client callback event triggered by client-side JavaScript and retrieves the appropriate child rows given the parent’s ID (passed as the eventArgument parameter). Because JavaScript isn’t going to be able to work with native .NET structures, the response to client callbacks is always going to be a string. In this case, the code used the pipe (|) and double-pipe (||) characters as column and row delimiters respectively.

Figure 22.4 shows a sample of what a page looks like that was populated using client callbacks. Keep in mind that the first list box is populated on the initial page load, and the second two list boxes are populated dynamically using client-side JavaScript and server-side client callback events.

Figure 22.4 Using client callbacks.

Image

Summary

This chapter provided you with an in-depth introduction to the world of creating powerful applications using ASP.NET 2.0. You learned the basics of how ASP.NET takes ASPX files and C# files and merges them into an assembly that is then used to service requests from users. This chapter also provided an overview of all of the stock controls that ship with ASP.NET, including the new controls specific to ASP.NET 2.0 such as the GridView, all of the integrated security controls such as Login and LoginView, and site navigation controls such as the SiteMapPath and the powerful new Menu control. Finally, the chapter concluded by giving you sample code for working with postbacks and event handling, and even a glimpse at the high-performance client/server hybrid client callback feature. At this point, you should be well equipped to take your ASP.NET learning to the next level and start diving into some of the amazing features of ASP.NET 2.0 such as personalization, customization, data-driven applications, security, web services, and much more.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.63.13