|
Chapter 1: Getting Started with Web Databases
Chapter 1 Getting Started with Web DatabasesIn this chapter, you'll learn:
With every passing moment, the Web becomes more interactive, more self-customizing, and generally more automated. Look closely at any large Web site, and you'll find a timeliness and consistency that no group of human Web designers could achieve by hand. Sites that offer news, weather, sports, online shopping, technical support, and searches of the entire Web provide many such examples. Creating a large site containing, say, several thousand pages is at best difficult and tedious. Imparting a consistent appearance is a major challenge. And even if you succeed in setting up such a large site initially, keeping it up to date by hand is essentially impossible. It's obvious that these large sites consist primarily of front-end Web pages displaying back-end databases. They are, in short, database-driven Web sites, and this is a concept applicable to large and small sites alike. The program code that makes database-driven Web sites possible runs not on the visitor's browser, but on the Web server. Code running on the browser is fine for running simple animations and making simple changes to the display, but getting the same piece of browser-side code to run on all versions of all browsers on all platforms is nearly an impossible task. In addition, code running on the browser has little or no access to databases, file space, services, connectivity, and other centralized resources on the Web server. Accessing server-side resources requires server-side code, and that's what this book teaches you to write.
Selecting Server-Side ToolsWhen a Web server delivers a so-called static Web pagesuch as an HTML file you created in Notepadit basically reads the file from the server's disk and transmits itunchangedout the network port. The fact that the Web server makes no changes to the HTML file accounts for the term static Web page. Loading the file into your browser from disk and loading it over the network produce the same results.The Web pages a visitor receives from a database-driven Web site don't come directly from the server's disk. Instead, requesting a database-driven Web page triggers a program that runs on the server, creates a custom Web page, and sends it to the visitor's browser. This provides tremendous flexibility compared to coding each possible response as a static Web page, storing all the required pages on disk, and somehow keeping them all up to date. For several years, Microsoft has been including a server-side programming technology called Active Server Pages (ASP) with all its Web servers. The ASP approach intermixes program codeusually coded in Microsoft Visual Basic Scripting Edition (VBScript)with ordinary HTML. In this way, developers can code the constant portions of their Web pages as they always havein ordinary HTMLand insert program code where they want customized content to appear. ActiveX Data Objects, another Microsoft technology, provides a way that Active Server Pages can query and update databases. The ASP approach has achieved great popularity, but as more and more developers use it for more and more complex applications, some limitations have become apparent:
To resolve these issues and more, Microsoft decided to make a fantastically upgraded ASP facility a major part of its .NET initiative. ASP.NET, the new release, addresses every major deficiency of the old ASP.
With ASP.NET, you can create your own program objectswith methods, properties, and all the other accoutrements you wantin essentially the same way that you create Web pages. In addition, you can create your own HTML tags. Once you define such a tag, you can use it in any number of Web pages. Whenever an ASP.NET page uses the new tag, code you supply runs on the Web server and creates HTML for transmission to the browser. You could, for example, create a tag that displays your name, your contact information, the date and time, or the thumbnail version of a picture.
As you might expect, much of this book concentrates on the use of ASP.NET and Visual Basic .NET. A list of additional technologies you'll need to know follows. Except for the basics of HTML and Microsoft Visual Basic, which you should already know, this book will explain every one of them.
You don't need to be an expert database designer to develop Web database pages, but you do need to understand how to create the necessary databases. Chapter 6 should provide enough assistance to get you started.
Chapter 7 provides a concise introduction to ADO.NET. In addition, nearly every example in the book will show you how to use ADO.NET in one way or another.
Most Web database pages construct their own SQL statements, often incorporating options or search values received from the Web visitor. Developing database pages thus requires at least a passing knowledge of SQL. Chapter 6 provides an introduction to SQL and shows how Access can write most of your SQL statements for you.
Comprehensive books on all these topics are widely available, but as a group they're too expensive and intimidating for beginning Web database developers. Beginners need only a small subset of this information, but they need it clearly explained in an integrated, cohesive way. In short, they need a cookbook. Web Database Development Step by Step .NET Edition is that cookbook. Using simple yet practical examples, the book shows how to take a database you've designed in Access, copy it to a Web server, and write Web pages for query and update. The emphasis here is on learning by examplenot on long, overly detailed text.
Upgrading from ASP to ASP.NETFew, if any, ASP pages will run unmodified as ASP.NET pages. The differences between the old and new versions of Visual Basic and ASP are simply too great. Fortunately, Microsoft has taken care to ensure that the two versions of ASP can coexist on the same server. Traditional ASP pages have a .asp filename extension and invoke the same Active Server Page interpreter that they always have. ASP.NET pages have a .aspx filename extension and invoke the ASP.NET processor. When legacy ASP pages need to start using ASP.NET features, you can fix or rewrite the code one page at a time.This book makes little mention of traditional ASP techniques and their cousins, traditional ADO techniques. These are unchanged from the book Web Database Development Step by Step (2000), which is still available from Microsoft Press.
Preparing Your EnvironmentEven with no more explanation than the preceding few pages, you should understand by now that ASP.NET pages contain program code that runs on a Web server. The server loads the ASP.NET page into memory, runs the code, and sends the resulting HTML to the browser. ASP.NET pages won't work unless a properly configured Web server delivers them.There are three requirements for proper configuration:
Other servers lack the software to process the Visual Basic .NET code, the software to process the databases, or both. Windows 2000 Professional and Windows XP Professional both include Web server software you can use to develop and test ASP.NET pages on your own PC.
You can find details about setting up your Web server in Chapter 2. All the examples in this book use Microsoft Access databases because a complete set of Access drivers is available to every reader, while SQL Server is available to a relative few. You're perfectly free to use Access for any database-driven Web sites you create, but you should understand that SQL Server is faster, more reliable, and more scalable than Access. For applications of any significant size or volume, you should definitely consider Microsoft SQL Server.
Creating a Simple Web Database DisplayIf you're at all like most readers, you'll agree that nothing is better for grasping the key concepts of an unfamiliar technology than a concrete, working example. The rest of this chapter will therefore explain how to create a simple ASP.NET Web page that reads the Access database shown in the graphic below and produces the Web page shown on the next page.Be forewarned, however, that there's a reason for the rest of the book to exist. The example doesn't explain how to set up and configure your Web server, for example, and it glosses over a number of important details. Don't be surprised if something piques your interest and sends you scurrying elsewhere in the book or to the index. Nevertheless, if your Web server is properly set up and you avoid typing errors, the example will work. Creating the example involves four fundamental steps:
Create a new ASP.NET file Creating a Web database page begins the same as creating any other type of Web page. This process should already be familiar to you, but in any case, here it is. If you prefer not to type the code for this example, refer to the members.aspx file in the ch01 folder you installed from the companion CD.
<html> This is perfectly ordinary HTML code. If you don't understand this much HTML, you might want to buy a beginner book on that topic before proceeding here.
Add code to read the database and write corresponding HTML This is the good partthe part you bought this book to see. You'll enter the code that extracts the member data from the database and presents it as HTML. The chapters in Part 2 will explain more fully the ADO.NET technology that's introduced here.
<asp:DataGrid id="gridMbrs" runat="server" /> Whoa! Even a cursory examination will reveal that this is no standard HTML tag. For one thing, the tag name asp:DataGrid is unknown to any browser. It is known, however, to ASP.NET, and that's all that counts. The ASP.NET software on the Web server will find this tag and convert it into program code that sends perfectly ordinary HTML to the Web visitor's browser. ASP.NET recognizes several dozen kinds of tags that have names beginning with asp:. Collectively, ASP.NET calls them WebControls. The asp:DataGrid control displays data in terms of rows and columns. This is perfect for displaying the rows and columns that result from querying a database. The attribute id="gridMbrs" gives the DataGrid a name. If the DataGrid didn't have a name, the code in the following steps would have no way of filling it with data. The runat="server" attribute tells ASP.NET that it should process this tag on the Web server. You might think that the oddball tag name asp:DataGrid would provide all the indication ASP.NET needs, but if so, you'd be wrong. If you forget to code runat="server", ASP.NET won't look at the tag name or, for that matter, anything else within the angle brackets. Notice the slash mark just before the closing angle bracket. ASP.NET demands a closing tag for each tag it encounters. A closing tag marks the end of the content that an HTML or XML tag affects. This is similar to the way a conventional <b> tag, which starts bold text, requires a </b> closing tag to return to plain text. The code for the DataGrid could have been
<asp:DataGrid id="gridMbrs" runat="server"> but since there's no content between the opening and closing tags, the single-tag version above is equivalent and saves you a bit of typing. This one tag is all the code you need to put in the body of the Web page. The ASP.NET software on the Web server will read this tag into memory. Then code developed in the next few steps will load it with data. When the code finishes, ASP.NET will send the Web visitor's browser the HTML necessary to display the data in an HTML table.
<%@ Page Language="vb" Debug="true" %> The first line tells ASP.NET that the default programming language for this page is Visual Basic ("vb"), and that ASP.NET should display debugging information if a serious failure occurs. The second line makes object classes in the System.Data namespace available to this page. As in most object-oriented systems, an ASP.NET class is a template for a type of object. A namespace is the name of a group of classes lumped together for convenience. The System.Data namespace contains various classes that are useful for working with databases. The third line makes classes in the System.Data.OleDb namespace available to this page. This namespace contains classes that are useful for accessing databases by means of a programming interface called OLE DB. Whenever you're using an Access or Oracle database, you'll need to import the System.Data.OleDb namespace. You can also use this namespace to access SQL Server databases, but the System.Data.SqlClient namespace is much more efficient.
<script runat="server"> These tags mark the beginning and the end of a so-called code declarations block. Code within such tags typically consists of variables, subroutines, functions, and classes that ASP.NET invokes automatically or that you invoke explicitly from other parts of your code. The attribute runat="server" tells ASP.NET to compile and run this code on the Web server and not on the browser. ASP.NET still uses the <% and %> tags that were common in classic ASP, but calls each instance a code render block. These blocks appear in line with HTML, and ASP.NET executes them as the page is leaving the server. The code <%=now%>, for example, replaces itself with the current date and time as the page leaves the Web server. The <% and %> tags also enclose directives like the @ Page and @ Import statements you coded earlier in this example. Code that the Web server should store for later execution is marked with <script runat="server"> and </script> tags. Typically, this code consists of subroutines and functions that ASP.NET invokes automatically or that you invoke explicitly from other parts of your code. Significantly, you can't define functions, subroutines, and classes within <% and %> tags. Likewise, you can't put directives or ordinary HTML between <script runat="server"> and </script> tags
Sub Page_Load(sender As Object, e As EventArgs) Here are the salient points regarding this code:
ASP.NET Page Events
The argument sender As Object receives a pointer to the object that triggered the eventthe Page object, in this case. In this example, an extra pointer to the Page object serves little purpose. This argument is more useful for event handlers that receive all events from a control that contains a collection of other controls. The argument e As EventArgs receives an object that contains any relevant information pertaining to the event that caused the subroutine to run. This is another argument that serves little purpose in this instance.
Dim conClsf As OleDbConnection
The first line creates a variable named conClsf that will point to an OleDbConnection object. It's worth noting at this point that ASP.NET pages use the full Visual Basic .NET programming language, and not a subset like Visual Basic Scripting Edition (VBScript). Unlike earlier forms of Visual Basic:
Line 2 contains a comment that marks (in bold) where additional Dim statements will go. The next three lines create an OLE DB connection to the database. Because this statement contains the keyword New, Visual Basic .NET will construct a new object for this purpose. The constructor method accepts one argument, a string expression called an OLE DB Connection string. This string has two parts, each ending with a semicolon:
These are the two pieces of information ADO.NET needs to open the database. The expression Server.MapPath("classified.mdb") in line 4 warrants a bit of explanation. Any file name you specify in the Data Source= portion of a connection string must be a local, fully qualified file name such as C:\InetPub\wwwroot\webdbpgm\ch01\classified.mdb. This requirement presents a problem because in most cases you don't know where in the Web server's file system your Web site begins. You do, however, know the URL of every file in your site, and this is where the Server.MapPath method comes in. Server.MapPath converts a relative URL to a local, fully qualified file location. Creating a connection object doesn't actually open the connection; for that, you must call the connection's Open method. The statement on line 6 does this. Line 7 is a comment that shows where the next step will supply more code for processing the database. Line 8 closes the database connection. The .NET framework is very good about cleaning up objects you leave in memory when the page ends, but even so, it's good to be tidy and clean up any objects you use.
Dim cmdMbrs As OleDbCommand Then replace the second comment with this code:
cmdMbrs = New OleDbCommand( _ The first three lines create the OleDbCommand object and the last line destroys it. Within the first three lines, the database command appears on line 2. This is a SQL statement that retrieves all columns ("*") from the members table and returns them in order by the memberid field. Line 3 specifies the database connection that you've just created. The comment in line 4 shows where additional code will go. If the example were using SQL Server instead of Access, it would create a SqlDbCommand object instead of an OleDbCommand object.
To create, open, and close the DataReader, first add the following statement after the other two Dims:
Dim rdrMbrs As OleDbDataReader Then replace the comment "Code to process database will go here" with the following code:
rdrMbrs = cmdMbrs.ExecuteReader The first line creates the DataReader by executing the command you've stored in the OleDbCommand object named rdrMbrs. Of course, it runs the command against the connection specified in the same object. The last line closes the DataReader and frees up any resources it used. Once again, it's best to be tidy.
gridMbrs.DataSource = rdrMbrs The first statement tells the DataGrid object gridMbrs that on demand, it should fill its rows and columns from the rdrMbrs DataReader. The second statement actually makes this happen.
Here's the completed Web page, including the code from the first procedure. Now that you understand each piece, the page should make sense when assembled.
<%@ Page Language="vb" Debug="true" %> If you're satisfied that you entered the page correctly, save it as members.aspx. Note in particular the filename extension .aspx. If you save the file with a .asp filename extension, the old ASP processor will try to interpret the page and surely display more error messages than you care to write home about. If you save the file with a .htm filename extension, the server won't recognize or execute the Visual Basic .NET code at all. Copy the Web page and the database onto the Web server To see the Web database page in action, you must copy both the members.aspx file and the classified.mdb database to a properly configured location on your Web server. The upload method doesn't matter; you can keep doing whatever you've been doing to upload ordinary Web pages. For ASP.NET pages to work, however, all the following must be true:
Run the page and view the results After you've uploaded your page to a properly configured Web server, you can test it simply by typing its URL into your browser. If all goes well, you'll get the results shown in this figure: Three results you shouldn't get:
These errors are usually the result of your Web server not executing an ASP.NET page as a program, but instead delivering it as an ordinary Web page. If this happens to you, either move the members.aspx and classified.mdb files to an executable folder or ask the server administrator to mark the existing folder as executable. You'll also get incorrect results by using your browser to open the members.aspx file directly from disk. The scripts in an ASP.NET page need to be processed and executed by a Web server; it's the result of that execution that you finally see in the Web browser. The following graphic shows typical results from a typing error in the Visual Basic .NET code. There are far too many possible error messages to describe in a book this size, but in most cases the message will supply a line number or an object name to identify the location of the error. If you get an error message referring to an invalid or unknown database format, either the .mdb file is corrupted, or you've somehow converted it to a version of Access older than Access 98. If you receive an error page that's much less informative than the one in the previous figure, it's probably because you're not browsing the page on the Web server's console and an option called customErrors is defaulting to On. The short way to correct this error is to open your text editor, enter the following lines, and save them in a file called web.config that's located in the same folder as the members.aspx page, in your application's root folder, or anywhere between.
<configuration> For the more detailed version, refer to the section "Configuring ASP.NET Applications" in Chapter 2. Once you get correct output, it's interesting to use your browser's View Source command and look at the HTML received. As shown in the following figure, the browser receives not the ASP.NET code, but ordinary HTML. The Web server executes the ASP.NET code before transmitting the Web page to the Web visitor. Therefore, instead of receiving the ASP.NET code, the browser receives any HTML the ASP.NET code generates.
What's Next?This chapter obviously skipped over a great many details in introducing the members.aspx example. You might be wondering, for example:
Well, you're in luckthe rest of the book is specifically designed to answer these questions and many more.
SummaryThis chapter introduced the concept of Web database pages, itemized the basic technologies involved, and described the general level of knowledge you'll need to benefit from this book. It also presented a simple Web database example.The next part of the bookPart 2, "Key Concepts"consists of six chapters full of background material. Depending on your background, you can study them judiciously, skim them for good parts, or ignore them for now and come back as needed. Part 3, "Developing Applications," will get back to coding complete Web pages.
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||