Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Pro CSharp And The .NET 2.0 Platform (2005) [eng]

.pdf
Скачиваний:
111
Добавлен:
16.08.2013
Размер:
10.35 Mб
Скачать

824CHAPTER 22 DATABASE ACCESS WITH ADO.NET

the wizard has created a new type deriving from DataSet named CarsDataSet. As you can see in Figure 22-24, this class type defines a number of members that allow you select, modify, and update its contents.

Figure 22-24. The strongly typed DataSet

Once the wizard completes its task, it places a member variable of type CarDataSet within your Form’s *.Designer.cs file (which is the same member variable manipulated in the Load event of your Form):

partial class MainForm

{

...

private CarsDataSet carsDataSet;

}

The Autogenerated Data Component

In addition to the strongly typed DataSet, the wizard generated a data component (named InventoryTableAdapter in this case) that encapsulates the underlying data connection, data adapter, and command objects used to interact with the Inventory table:

public partial class InventoryTableAdapter : System.ComponentModel.Component

{

// field data for data access.

private System.Data.SqlClient.SqlDataAdapter m_adapter; private System.Data.SqlClient.SqlConnection m_connection; private System.Data.SqlClient.SqlCommand[] m_commandCollection;

...

}

As well, this component defines custom Fill() and Update() methods that are tailor-made to operate on your CarsDataSet, in addition to a set of members used to insert, update, or delete row

CHAPTER 22 DATABASE ACCESS WITH ADO.NET

825

data from the internal Inventory table. I’ll leave it up to interested readers to dive into the implementation details of each member. The good news is that after all your work in this chapter, the code behind each member should look quite familiar.

Note If you are interested in taking a deeper look at the ADO.NET object model, including the numerous Visual Studio 2005 designers, check out Pro ADO.NET 2.0 by Sahil Malik (Apress, 2005).

Summary

ADO.NET is a new data access technology developed with the disconnected n-tier application firmly in mind. The System.Data namespace contains most of the core types you need to programmatically interact with rows, columns, tables, and views. As you have seen, the .NET platform ships with numerous data providers that allow you to leverage the connected and disconnected layers of ADO.NET.

Using connection objects, command objects, and data reader objects of the connected layer, you are able to select, update, insert, and delete records. As you have seen, command objects support an internal parameter collection, which can be used to add some type safety to your SQL queries and are quite helpful when triggering stored procedures.

The centerpiece of the disconnected layer is the DataSet. This type is an in-memory representation of any number of tables and any number of optional interrelationships, constraints, and expressions. The beauty of establishing relations on your local tables is that you are able to programmatically navigate between them while disconnected from the remote data store.

You also examined the role of the data adapter in this chapter. Using this type (and the related

SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand properties), the adapter can resolve changes in the DataSet with the original data store. Also, you learned about the connected layer of ADO.NET and came to understand the role of data reader types.

P A R T 5

■ ■ ■

Web Applications and XML

Web Services

C H A P T E R 2 3

■ ■ ■

ASP.NET 2.0 Web Pages and Web

Controls

Until now, all of the example applications in this text have focused on console-based and Windows Forms front ends. In this chapter and the next, you’ll explore how the .NET platform facilitates the construction of browser-based presentation layers. To begin, you’ll quickly review a number of key web-centric concepts (HTTP, HTML, client-side, and server-side script) and the role of the web server (including the ASP.NET development server, WebDev.WebServer.exe).

With this web primer out of the way, the remainder of this chapter concentrates on the composition of ASP.NET (including the enhanced code-behind model) and how to work with ASP.NET web controls. As you will see, ASP.NET 2.0 provides a number of new web controls, a new “master page” model, and various customization techniques.

The Role of HTTP

Web applications are very different animals from traditional desktop applications (to say the least). The first obvious difference is that a production-level web application will always involve at least two networked machines (of course, during development it is entirely possible to have a single machine play the role of both client and server). Given this fact, the machines in question must agree upon a particular wire protocol to determine how to send and receive data. The wire protocol that connects the computers in question is the Hypertext Transfer Protocol (HTTP).

When a client machine launches a web browser (such as Netscape Navigator, Mozilla Firefox, or Microsoft Internet Explorer), an HTTP request is made to access a particular resource (such as an *.aspx or *.htm file) on the remote server machine. HTTP is a text-based protocol that is built upon a standard request/response paradigm. For example, if you navigate to http://www. IntertechTraining.com, the browser software leverages a web technology termed Domain Name Service (DNS) that converts the registered URL into a four-part, 32-bit numerical value (aka an IP address). At this point, the browser opens a socket connection (typically via port 80) and sends the HTTP request for the default page at the http://www.IntertechTraining.com website.

Once the hosting web server receives the incoming HTTP request, the specified resource may contain logic that scrapes out any client-supplied input values (such as values within a text box) in order to format a proper HTTP response. Web programmers may leverage any number of technologies (CGI, ASP, ASP.NET, Java servlets, etc.) to dynamically generate the content to be emitted into the HTTP response. At this point, the client-side browser renders the HTML emitted from the web server. Figure 23-1 illustrates the basic HTTP request/response cycle.

829

830 CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

Figure 23-1. The HTTP request and response cycle

Another aspect of web development that is markedly different from traditional desktop programming is the fact that HTTP is an essentially stateless wire protocol. As soon as the web server emits a response to the client, everything about the previous interaction is forgotten. Therefore, as a web developer, it is up to you take specific steps to “remember” information (such as items in

a shopping cart) about the clients who are currently logged on to your site. As you will see in the next chapter, ASP.NET provides numerous ways to handle state, many of which are commonplace to any web platform (session variables, cookies, and application variables) as well as some new techniques (view state, control state, and the cache).

Understanding Web Applications and Web Servers

A web application can be understood as a collection of files (*.htm, *.asp, *.aspx, image files, etc.) and related components (such as a .NET code library) stored within a particular set of directories on a given web server. As shown in Chapter 24, web applications have a specific life cycle and provide numerous events (such as initial startup or final shutdown) that you can hook into.

A web server is a software product in charge of hosting your web applications, and it typically provides a number of related services such as integrated security, File Transfer Protocol (FTP) support, mail exchange services, and so forth. Internet Information Server (IIS) is Microsoft’s enterprise-level web server product, and as you would guess, it has intrinsic support for classic ASP as well as ASP.NET web applications.

When you build ASP.NET web applications, you will often need to interact with IIS. Be aware, however, that IIS is not automatically selected when you install the Windows Server 2003 or Windows XP Professional Edition (you can’t install IIS on the Home editions of Windows). Therefore, depending on the configuration of your development machine, you may be required to manually install IIS before proceeding through this chapter. To do so, simply access the Add/Remove Program applet from the Control Panel folder and select Add/Remove Windows Components.

Note Ideally, your development machine will have IIS installed before you install the .NET Framework. If you install IIS after you install the .NET Framework, none of your ASP.NET web applications will execute correctly (you will simply get back a blank page). Luckily, you can reconfigure IIS to host .NET applications by running the aspnet_regiis.exe command-line tool (using the /i flag).

Assuming you have IIS properly installed on your workstation, you can interact with IIS from the Administrative Tools folder (located in the Control Panel folder). For the purposes of this chapter, you are concerned only with the Default Web Site node (see Figure 23-2).

CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

831

Figure 23-2. The IIS applet

Working with IIS Virtual Directories

A single IIS installation is able to host numerous web applications, each of which resides in a virtual directory. Each virtual directory is mapped to a physical directory on the local hard drive. Therefore, if you create a new virtual directory named CarsRUs, the outside world can navigate to this site using a URL such as http://www.CarsRUs.com (assuming your site’s IP address has been registered with the world at large). Under the hood, the virtual directory maps to a physical root directory such as C:\inetpub\wwwroot\AspNetCarsSite, which contains the content of the web application.

When you create ASP.NET web applications using Visual Studio 2005, you have the option of generating a new virtual directory for the current website. However, you are also able to manually create a virtual directory by hand. For the sake of illustration, assume you wish to create a simple web application named Cars. The first step is to create a new folder on your machine to hold the collection of files that constitute this new site (e.g., C:\CodeTests\CarsWebSite).

Next, you need to create a new virtual directory to host the Cars site. Simply right-click the Default Web Site node of IIS and select New Virtual Directory from the context menu. This menu selection launches an integrated wizard. Skip past the welcome screen and give your website a name (Cars).

Next, you are asked to specify the physical folder on your hard drive that contains the various files and images that represent this site (in this case, C:\CodeTests\CarsWebSite).

The final step of the wizard prompts you for some basic traits about your new virtual directory (such as read/write access to the files it contains, the ability to view these files from a web browser, the ability to launch executables [e.g., CGI applications], etc.). For this example, the default selections are just fine (be aware that you can always modify your selections after running this tool using various right-click Property dialog boxes integrated within IIS). When you are finished, you will see that your new virtual directory has been registered with IIS (see Figure 23-3).

Figure 23-3. The Cars virtual directory

832 CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

The ASP.NET 2.0 Development Server

ASP.NET 2.0 ships with a lightweight web server named WebDev.WebServer.exe. This utility allows developers host an ASP.NET 2.0 web application outside the bounds of IIS. Using this tool, you can build and test your web pages from any directory on your machine (which is quite helpful for team development scenarios and for building ASP.NET 2.0 web programs on Windows XP Home Edition, which does not support IIS).

Note WebDev.WebServer.exe cannot be used to test classic ASP web applications.

When building a website with Visual Studio 2005, you have the option of using WebDev.WebServer.exe to host your pages. However, you are also able to manually interact with this tool from a .NET command prompt. If you enter the following command:

WebDev.WebServer.exe -?

you will be presented with a message box that describes the valid command-line options. In a nutshell, you will need to specify an unused port (via the /port: option), the root directory of the web application (via the /path: option), and an optional virtual path using the /vpath: option (if you do not supply a /vpath: option, the default is simply /). Consider the following usage:

WebDev.WebServer.exe /port:12345 /path:"C:\CodeTests\CarsWebSite"

Once you have entered this command, you can launch your web browser of choice to request pages. Thus, if the CarsWebSite folder had a file named MyPage.aspx, you could enter the following URL:

http://localhost:12345/CarsWebSite/MyPage.aspx

Many of the examples in this chapter and the next will make use of WebDev.WebServer.exe via Visual Studio 2005. Be aware that this web server is not intended to host production-level web applications. It is purely intended for development and testing purposes.

Note The Mono project (see Chapter 1) provides a free ASP.NET plug-in for the Apache web server. Check out http://www.mono-project.com/ASP.NET for details.

The Role of HTML

Once you have configured a directory to host your web application, you need to create the content itself. Recall that web application is simply the term given to the set of files that constitute the functionality of the site. To be sure, a vast number of these files will contain syntactic tokens defined by the Hypertext Markup Language (HTML). HTML is a standard markup language used to describe how literal text, images, external links, and various HTML-based GUI widgets are rendered by the client-side browser.

This particular aspect of web development is one of the major reasons why many programmers dislike building web-based programs. While it is true that modern IDEs (including Visual Studio 2005) and web development platforms (such as ASP.NET) generate much of the HTML automatically, you will do well to have a working knowledge of HTML as you work with ASP.NET. While this section will most certainly not cover all aspects of HTML (by any means), let’s check out some basics.

CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

833

HTML Document Structure

An HTML file consists of a set of tags that describe the look and feel of a given web page. As you would expect, the basic structure of an HTML document tends to remain the same. For example, *.htm files (or, alternatively, *.html files) open and close with <html> and </html> tags, typically define a <body> section, and so forth. Keep in mind that HTML is not case sensitive. Therefore, in the eyes of the hosting browser, <HTML>, <html>, and <Html> are identical.

To illustrate some HTML basics, open Visual Studio 2005, insert an empty HTML file using the File New File menu selection, and save this file under your C:\CodeTests\CarsWebSite directory as default.htm. As you can see, the initial markup is uneventful:

<html>

<body>

</body>

</html>

The <html> and </html> tags are used to mark the beginning and end of your document. As you may guess, web browsers use these tags to understand where to begin applying the rendering formats specified in the body of the document. The <body> scope is where the vast majority of the actual content is defined. To spruce things up just a bit, define a title for your page as so:

<html>

<head>

<title>This Is the Cars Website</title> </head>

<body>

</body>

</html>

As you would guess, the <title> tags are used to specify the text string that should be placed in the title bar of the calling web browser.

HTML Form Development

The real action of an *.htm file occurs within the scope of the <form> elements. An HTML form is simply a named group of related UI elements used to gather user input, which is then transmitted to the web application via HTTP. Do not confuse an HTML form with the entire display area shown by a given browser. In reality, an HTML form is more of a logical grouping of widgets placed in the

<form> and </form> tag set:

<html>

<head>

<title>This Is the Cars Web Site</title> </head>

<body>

<form id="defaultPage" name="defaultPage">

<!-- Insert web content here ->

</form>

</body>

</html>

This form has been assigned the ID and name of “defaultPage”. Typically, the opening <form> tag supplies an action attribute that specifies the URL to which to submit the form data, as well as the method of transmitting that data itself (POST or GET). You will examine this aspect of the <form>