Chapter 1. Getting Started with Web Databases

Getting Started with Web Databases

In this chapter, you’ll learn:

How to create a new ASP.NET Web page.

How to write code to read and display a database table.

How to run the ASP.NET Web page on your Web server.

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 Tools

When a Web server delivers a so-called static Web page—such as an HTML file you created in Notepad—it basically reads the file from the server’s disk and transmits it—unchanged—out 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 code—usually 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 have—in ordinary HTML—and 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:

  • VBScript isn’t suited for developing reusable modules. Developers can store functions and subroutines in separate files and include the same file in multiple Web pages, but this makes tracing program code in a large project extremely difficult.

  • Neither ASP nor VBScript has access to the full functionality of the underlying Microsoft Windows operating system. Tasks such as sending mail, storing files uploaded with HTML forms, manipulating pictures, and writing to the system event log all require the use of Microsoft, third-party, or custom-written ActiveX controls.

  • The practice of putting a program where its output should appear in a Web page doesn’t scale well. In complex pages, code can end up in all sorts of odd places. This makes it difficult to trace and maintain.

  • At many large sites, Web page designers and Web page programmers are two very different groups of people. With both groups accessing the ASP files, conflicts and confusion inevitably arise.

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.

  • ASP.NET uses the full Visual Basic .NET programming language. This is the most capable and most feature-complete version of Visual Basic ever released. You can also code ASP.NET pages in C# or any other language that has a .NET compiler.

  • Visual Basic .NET, C#, and other supported languages have access to the entire set of .NET system-level objects. Essentially, this means an ASP.NET page can do anything Windows can do.

  • ASP.NET clearly separates program code from Web page layout code. You can even store the two kinds of code in different files, and then change one without changing the other. You can still mix program code and HTML code if you want to, but after you become accustomed to the new structure, you’ll seldom if ever have the desire.

    With ASP.NET, you can create your own program objects—with methods, properties, and all the other accoutrements you want—in 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.

  • HTML. Despite its many limitations, Hypertext Markup Language remains the fundamental technology for controlling the structure and appearance of Web pages. This book assumes you’re comfortable enough with HTML to hand-code simple Web pages.

  • Microsoft Visual Basic .NET. This is the programming language of choice for ASP. To understand this book, you don’t need great knowledge of Visual Basic, but you should be at least somewhat comfortable with Visual Basic structure and syntax. For example, you should recognize an If Then...Else...End If structure or a For...Next loop when you see one.

    Note

    Many Web developers avoid using Visual Basic within Web pages because Netscape Navigator doesn’t support it. However, because ASP.NET pages run on the Web server rather than on the browser, Netscape browser support isn’t an issue.

  • Database design and implementation. The first step in using any database is, of course, designing its tables and fields. The second step is implementing this structure with the database software. The third and fourth steps are adding and querying data—which are totally dependent on the first two steps.

    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.

  • Microsoft ADO.NET. Accessing any database from a programming language obviously requires some sort of software interface. In the context of ASP.NET, this is usually ADO.NET. ASP.NET pages can still use the old ADO methods if you want, but this is something you’ll seldom, if ever, want to do.

    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.

  • Structured query language. Virtually all database systems accept commands from applications in a format called structured query language (SQL). Neither Microsoft Access—the primary database system covered in this book—nor Microsoft SQL Server are exceptions. ADO.NET accepts SQL commands from the application code and sends them to the database software, which executes them.

    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 example—not on long, overly detailed text.

Upgrading from ASP to ASP.NET

Few, 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 Environment

Even 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:

  • The Web server software must be Internet Information Services running on Windows 2000 Professional, Server, or Advanced Server, or Windows XP Professional.

    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.

    Note

    Windows XP Home Edition is a notable omission from the previous list because, unlike Windows XP Professional, it doesn’t include Web server software. If you’re currently running Windows XP Home and need to run a Web server on your own PC, you should upgrade to Windows XP Professional.

  • The .NET Framework must be installed on the server.

  • Any Web server folder where you put the ASP.NET pages must be flagged as executable. This flagging is something the server’s administrator must do.

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.

Note

Switching an ASP.NET page from Access to SQL Server is very easy. Where the choice of DBMS requires different code, the book will explain this.

Creating a Simple Web Database Display

If 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.

Creating a Simple Web Database Display
Creating a Simple Web Database Display

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:

  1. Create a new ASP.NET file.

  2. Add code to read the database and write corresponding HTML.

  3. Copy the ASP.NET file and the database onto the Web server.

  4. Run the page and view the results.

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.

  1. Start your favorite HTML editor. This can be a simple text editor, such as Notepad, a WYSIWYG editor such as Microsoft FrontPage or Microsoft Visual Studio .NET, or anything in between.

    Tip

    When choosing an editor, you should be aware that ASP.NET pages frequently contain tags that, although enclosed in < > marks, are decidedly not standard HTML. These tags can seriously confuse an HTML editor that’s not specifically designed to work with ASP.NET pages. If you decide to use FrontPage, make sure it’s FrontPage 2002 or later.

  2. If you choose a WYSIWYG editor, switch it to a view that shows the HTML code.

  3. Create a new file.

  4. If the following statements aren’t already present, add them. Case doesn’t matter.

    <html>
    <head>
    <title>Classified Ad Members</title>
    </head>
    <body>
    <h1>Classified Ad Members</h1>
    </body>
    </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 part—the 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.

  1. First enter the tag shown below just before the </body> tag of your new Web page.

    <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">
    </asp:DataGrid>

    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.

    Tip

    If you forget to close an ASP.NET tag, you’ll get an error message when you try to run the page. In some cases, ASP.NET will complain that the tag containing the runat="server" attribute isn’t properly ended. In others, the error message will state that the HTML following the unclosed tag isn’t allowed within that tag.

  2. Making this ASP.NET page work properly requires setting a few options. To do this, add the following lines at the very top of the Web page (that is, before the <html> tag).

    <%@ Page Language="vb" Debug="true" %>
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Data.OleDb"%>

    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.

  3. The next task is to write some Visual Basic code that opens a connection to the database, reads the required data, and puts it into the DataGrid. To create an area where script code can reside, add the following statements right after the <head> statement.

    <script runat="server">
    </script>

    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

  4. Next, you must create a subroutine that ASP.NET will run every time it loads the page. This subroutine will open a connection to the database, retrieve the required records, and load the DataGrid with data. To start coding the subroutine, add the following lines between the <script runat="server"> and </script> tags you entered earlier.

    Sub Page_Load(sender As Object, e As EventArgs)
    End Sub

    Here are the salient points regarding this code:

    • The keyword Sub tells Visual Basic that this is the beginning of a subroutine.

    • Page_Load is the name of the subroutine. When ASP.NET finds a subroutine with this name, it automatically runs the code after loading the entire page into memory and before sending any HTML to the Web visitor.

    • This table lists the four events that occur whenever ASP.NET processes a Web page. The Page_Load event handler is by far the most commonly used.

    ASP.NET Page Events

    Event

    Event Handler

    Description

    Init

    Page_Init

    Occurs when ASP.NET initializes the page. No page elements are available at this time.

    Load

    Page_Load

    Occurs when ASP.NET has loaded all server controls into memory.

    PreRender

    Page_PreRender

    Occurs when ASP.NET is ready to render the page as HTML.

    Unload

    Page_Unload

    Occurs after ASP.NET has removed all server controls from memory.

    The argument sender As Object receives a pointer to the object that triggered the event—the 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.

    Note

    Most programmers find it easier to code sender As Object, e As EventArgs for every event handler than to figure out when they need it and when they don’t.

  5. To read the database, you must first open it. Therefore, enter the following code between the Sub and End Sub statements entered earlier.

    Dim conClsf As OleDbConnection
    ' Additional declarations will go here.
    conClsf = New OleDbConnection( _
             "Provider=Microsoft.Jet.OLEDB.4.0;" & _
             "Data Source=" & server.mappath("classified.mdb") &
             ";")
    conClsf.Open
    ' Code to process database will go here.
    conClsf.Close

    Note

    The ampersand (&) operator in Visual Basic joins two strings. The following expressions are equivalent:

    "a" & "b"
    "ab"

    The underscore (_) operator continues a line. That is, it tells Visual Basic to ignore the next line break following the underscore.

    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:

    • Visual Basic .NET no longer supports variants (the only data type that VBScript did support), so you must declare each variable to be a specific type.

    • Visual Basic .NET requires that you code a Dim statement for each variable name you use. You can turn this off by coding Explicit="false" in the @ Page directive, but experienced programmers never do this. They’d much rather receive a clear error message when they forget to declare a variable than spend hours tracking down a misspelled variable name.

    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:

    • The Provider= portion specifies that this is an Access database.

    • The Data Source= portion specifies its file location.

    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:InetPubwwwrootwebdbpgmch01classified.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.

  6. The next step involves creating an OleDbCommand object. This type of object stores a database command and a pointer to the database connection that will process it. To begin, declare the object variable by coding this statement just before the comment "Additional declarations will go here."

    Dim cmdMbrs As OleDbCommand

    Then replace the second comment with this code:

    cmdMbrs = New OleDbCommand( _
              "select * from members order by memberid", _
              conClsf)
    ' Code to process database will go here.
    CmdMbrs.Dispose

    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.

  7. An ADO.NET object called a DataReader will perform the job of actually retrieving data through the connection object. In all but the most unusual cases, a DataReader is the fastest and easiest way to retrieve data from a database. You can’t move randomly or backward through the records in a DataReader, and you can’t do updates, but since the example doesn’t need to do either of those things, the DataReader is the best ADO.NET object to use.

    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
    ' Code to process database will go here.
    rdrMbrs.Close

    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.

  8. The last step is to copy the data in the open DataReader into the DataGrid object from step 1. To do this, replace the comment "Code to process database will go here" with these lines of code:

    gridMbrs.DataSource = rdrMbrs
    gridMbrs.DataBind

    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" %>
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Data.OleDb"%>
    <html>
    <head>
    <script runat="server">
    Sub Page_Load(sender As Object, e As EventArgs)
      Dim conClsf As OleDbConnection
      Dim cmdMbrs As OleDbCommand
      Dim rdrMbrs As OleDbDataReader
      conClsf = New OleDbConnection( _
               "Provider=Microsoft.Jet.OLEDB.4.0;" & _
               "Data Source=" & _
               server.mappath("classified.mdb") & ";")
      conClsf.Open
      cmdMbrs = New OleDbCommand( _
               "select * from members order by memberid", _
               conClsf)
      rdrMbrs = cmdMbrs.ExecuteReader
      gridMbrs.DataSource = rdrMbrs
      gridMbrs.DataBind
      rdrMbrs.Close
      cmdMbrs.Dispose
      conClsf.Close
    End Sub
    </script>
    <title>Classified Ad Members</title>
    </head>
    <body>
    <h1>Classified Ad Members</h1>
    <asp:DataGrid id="gridMbrs" runat="server" />
    </body>
    </html>

    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:

  • Your browser must retrieve them from a Web server. It should be very clear by now that ASP.NET pages contain a variety of code that the Web server executes after retrieving the .aspx file from disk and before transmitting the finished page to the browser. If you load an .aspx page directly from disk into your browser, the Web server is out of the loop and your ASP.NET code won’t execute.

  • The .NET framework must be installed on the Web server. If someone else administers your Web server—perhaps someone at your Internet service provider or someone in your organization’s Information Technology department—they’ll need to install the .NET Framework for you. If you administer your own Web server—anything from a full-blown production server to a test server running on your own PC—you can perform the installation yourself. Chapter 2 provides guidance in this area, but in either case, the operating system will need to be Microsoft Windows XP Professional or Microsoft Windows 2000.

  • The folder where the members.aspx file resides must be marked as executable. Otherwise, the Web server will send all your ASP.NET code to the browser, with results that are ugly at best.

Note

You can find a copy of the classified.mdb database on the companion CD-ROM. Its location is D:webdbpgmch01classified.mdb; D is your CD-ROM drive letter.

Caution

When you copy files from a CD-ROM to your hard disk via Windows Explorer, Explorer marks the resulting file as read-only. This is unacceptable for Access databases. To turn off the read-only attribute, right-click the file, choose Properties from the shortcut menu, clear the Read Only check box, and then click OK. If you use the installer on the CD, you don’t need to worry about this, because the read-only attribute will be set to False automatically.

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:

Run the page and view the results

Three results you shouldn’t get:

  • A Web page displaying your Visual Basic .NET code

  • A Web page containing no database information

  • A prompt asking whether you’d like to download the page

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.

Run the page and view the results

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>
  <system.web>
     <compilation debug="true"/>
     <customErrors mode="Off"/>
  </system.web>
</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.

Run the page and view the results

What’s Next?

This chapter obviously skipped over a great many details in introducing the members.aspx example. You might be wondering, for example:

  • What if my Web server isn’t one of those named in Add code to read the database and write corresponding HTML?

  • How do I test ASP.NET pages on my own PC?

  • How do I create the database and organize the tables within it?

  • Querying records is fine, but how do I insert, update, and delete records?

  • How can I query and update databases by using HTML forms?

  • Can I watch my ASP.NET code as it runs, pause the execution, and inspect data values?

  • What’s XML, the Extensible Markup Language, and how does it apply to Web databases?

Well, you’re in luck—the rest of the book is specifically designed to answer these questions and many more.

Summary

This 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 book—Part 2—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, will get back to coding complete Web pages.

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

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