Web Applications Using Visual Studio .NET
We have examined the fundamentals of ASP.NET and have created some simple Web pages. To carry the story further it will be very helpful to start using Visual Studio .NET. Everything we do could also be accomplished using only the .NET Framework SDK, but our work will be much easier using the facilities of Visual Studio. A special kind of project, an "ASP.NET Web Application," creates the boilerplate code. The Forms Designer makes it very easy to create Web forms by dragging controls from a palette. We can add event handlers for controls in a manner very similar to the way event handlers are added in Windows Forms. In fact, the whole Web application development process takes on many of the rapid application development (RAD) characteristics typical of Visual Basic.
In this section we will introduce the Web application development features of Visual Studio by creating the first step of our Acme Travel Web site. We will elaborate on specific features of ASP.NET in later sections.
Form Designers for Windows and Web Applications
The basic look and feel of the Form Designers for Windows and Web applications is the same. You drag controls from a toolbox. You set properties in a Property window. You navigate between a code view and a designer view with toolbar buttons. In the following discussion we assume you have a basic familiarity with this visual paradigm. You may find it helpful to refer back to Chapter 7.
Hotel Information Web Page (Step 0)
We begin by creating a simple Web page that will display information about hotels. Dropdown listboxes are provided to show cities and hotels. Selecting a city from the first dropdown will cause the hotels in that city to be shown in the second dropdown. We obtain the hotel information from the Hotel.dll component, and we use data binding to populate the listboxes. As a source for the Hotel.dll and Customer.dll components used later, we provide a version of the GUI application from Chapter 7, AcmeGui. The Hotel.dll component we need in the following demonstration is in the folder AcmeGui. If you would like to follow along hands-on with Visual Studio, do your work in the Demos folder for this chapter. The completed project is in AcmeWeb\Step0.
CONFIGURING WEB SERVER CONNECTION
Before getting started you may wish to check, and possibly change, your Visual Studio Web Server Connection setting. The two options are File share and FrontPage. If you are doing all your development on a local computer, you might find File share to be faster and more convenient. To access this setting, select the Visual Studio menu Tools | Options.... Choose Web Settings underneath Projects. You can then set the Preferred Access Method by using a radio button, as illustrated in Figure 1417.
Figure 14-17 Configuring Web server connection preferred access method.
CREATING AN ASP.NET WEB APPLICATION
In Visual Studio select the menu File | New | Project....
In the New Project dialog box choose Visual Basic Projects as the Project Type and ASP.NET Web Application as the Template.
Enter http://localhost/Chap14/Demos/AcmeWeb as the location of your project, as illustrated in Figure 1418. This setting assumes you have made \OI\NetVb\Chap14 into a virtual directory with alias Chap14.
Figure 14-18 Creating a Visual Studio ASP.NET Web Application project.
Click OK. The project files will then be created in \OI\NetVb\Chap14\Demos\AcmeWeb. The VS.NET solution AcmeWeb.sln will then be created under MyDocuments\Visual Studio Projects\AcmeWeb.
USING THE FORM DESIGNER
Bring up the Toolbox from the View menu, if not already showing. Make sure the Web Forms tab is selected.
Drag two Label controls and two DropDownList controls onto the form.
Change the Text property of the Labels to City and Hotel. Resize the DropDownList controls to look as shown in Figure 1419.
Change the (ID) of the DropDownList controls to listCities and listHotels.
Figure 14-19 Using the Form Designer to add controls to the form.
INITIALIZING THE HOTELBROKER
Copy Hotel.dll from AcmeGui to Demos\AcmeWeb\bin.
In your AcmeWeb, project add a reference to Hotel.dll.
As shown in the following code fragment, in Global.asax, add the following line near the top of the file. (Use the View Code button to show the code.)
Add a public shared variable broker of type HotelBroker.
Add code to Application_Start to instantiate HotelBroker.
' Global.asax Imports System.Web Imports System.Web.SessionState Imports OI.NetVb.Acme Public Class Global Inherits System.Web.HttpApplication #Region " Component Designer Generated Code " ... Public Shared broker As HotelBroker Sub Application_Start(ByVal sender As Object, _ ByVal e As EventArgs) ' Fires when the application is started broker = New HotelBroker() End Sub ...
In WebForm1.aspx.vb add an Imports OI.NetVb.Acme statement, and declare a shared variable broker of type HotelBroker.
' WebForm1.aspx.vb Imports OI.NetVb.Acme Public Class WebForm1 Inherits System.Web.UI.Page ... Private Shared broker As HotelBroker ...
Imports OI.NetVb.Acme
DATA BINDING
Next we will populate the first DropDownList with the city data, which can be obtained by the GetCities method of HotelBroker. We make use of the data binding capability of the DropDownList control. You might think data binding is only used with a database. However, in .NET data binding is much more general, and can be applied to other data sources besides databases. Binding a control to a database is very useful for two-tier, client/server applications. However, we are implementing a three-tier application, in which the presentation logic, whether implemented using Windows Forms or Web Forms, talks to a business logic component and not directly to the database. So we will bind the control to an ArrayList.
The .NET Framework provides a number of data binding options, which can facilitate binding to data obtained through a middle-tier component. A very simple option is binding to an ArrayList. This option works perfectly in our example, because we need to populate the DropDownList of cities with strings, and the GetCities method returns an array list of strings.
The bottom line is that all we need to do to populate the listCities DropDownList is to add the following code to the Page_Load method of the WebForm1 class.
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here If Not IsPostBack Then broker = Global.broker Dim cities As ArrayList = broker.GetCities() listCities.DataSource = cities DataBind() End If End Sub
The call to DataBind() binds all the server controls on the form to their data source, which results in the controls being populated with data from the data source. The DataBind method can also be invoked on the server controls individually. DataBind is a method of the Control class, and is inherited by the Page class and by specific server control classes.
You can now build and run the project. Running a Web application under Visual Studio will bring up Internet Explorer to access the application over HTTP. Figure 1420 shows the running application. When you drop down the list of cities, you will indeed see the cities returned by the Hotel-Broker component.
Figure 14-20 Running the Web page to show information about cities.
INITIALIZING THE HOTELS
We can populate the second DropDownList with hotel data using a similar procedure. It is a little bit more involved, because GetHotels returns an array list of HotelListItem structures rather than strings. We want to populate the listHotels DropDownList with the names of the hotels. The helper method BindHotels loops through the array list of hotels and creates an array list of hotel names, which is bound to listHotels. Here is the complete code, which adds the logic for initializing the hotels for the first city (which has index 0).
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here If Not IsPostBack Then broker = Global.broker Dim cities As ArrayList = broker.GetCities() listCities.DataSource = cities Dim hotels As ArrayList = _ broker.GetHotels(CStr(cities(0))) BindHotels(hotels) DataBind() End If End Sub Private Sub BindHotels(ByVal hotels As ArrayList) Dim hotelNames As ArrayList = _ New ArrayList(hotels.Count) Dim hotel As HotelListItem For Each hotel In hotels hotelNames.Add(hotel.HotelName.Trim()) Next listHotels.DataSource = hotelNames End Sub
SELECTING A CITY
Finally, we implement the feature that selecting a city causes the hotels for the selected city to be displayed. We can add an event handler for selecting a city by double-clicking on the listCities DropDownList control. This is a shortcut for adding a handler for the primary event for the control. Another method for adding an event handler for this control is to select listCities from the first dropdown in the WebForm1.aspx.vb code window. You can then choose an event from the second dropdown, as illustrated in Figure 1421. The second method allows you to add a handler for any event of the control. Here is the code for the SelectedIndexChanged event:
Private Sub listCities_SelectedIndexChanged( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles listCities.SelectedIndexChanged Dim city As String = listCities.SelectedItem.Text Dim hotels As ArrayList = broker.GetHotels(city) BindHotels(hotels) DataBind() End Sub
Figure 14-21 Adding an event handler for a control.
Build and run the project. Unfortunately, the event does not seem to be recognized by the server. What do you suppose the problem is?
AUTOPOSTBACK
For an event to be recognized by the server, you must have a postback to the server. Such a postback happens automatically for a button click, but not for other events. Once this problem is recognized, the remedy is simple. In the Properties window for the cities DropDownList control, change the AutoPost-Back property to true. Figure 1422 illustrates setting the AutoPostBack property. The program should now work properly. The project is saved in the folder AcmeWeb\Step0.
Figure 14-22 Setting the AutoPastBack property of a DropDownList control.
DEBUGGING
One advantage of using Visual Studio for developing your ASP.NET applications is the ease of debugging. You can set breakpoints, single-step, examine the values of variables, and so forth, in your code-behind files just as you would with any other Visual Studio program. All you have to do is build your project in Debug mode (the default) and start the program from within Visual Studio using Debug | Start (or F5 at the keyboard or the toolbar button ).
As an example, set a breakpoint on the first line of the SelectedIndex-Changed event handler for listCities. Assuming you have set the AutoPost-Back property to True, as we have discussed, you should hit the breakpoint.
Deploying a Web Application Created Using Visual Studio
Developing a Web application using Visual Studio is quite straightforward. You can do all your work within Visual Studio, including testing your application. When you start a Web application within Visual Studio, Internet Explorer will be brought up automatically. And it is easy to debug, as we have just seen.
Deploying a Web application created using Visual Studio is also easy, but you need to be aware of a few things.
The Project | Copy Project... menu can be used to deploy a Web project from Visual Studio.
Visual Studio precompiles Web pages, storing the executable in the bin folder.
The Src attribute in the Page directive is not used. Instead, the Inherits attribute is used to specify the Page class.
The directory containing the Web pages must be marked as a Web application. This marking is performed automatically by Visual Studio when you deploy the application. If you copy the files to another directory, possibly on another system, you must perform the marking as an application yourself, which you can do using Internet Services Manager. (We will discuss this procedure later in the chapter.)
USING PROJECT | COPY PROJECT...
To illustrate using Visual Studio to deploy a Web project, let's deploy the Acme Hotel Information page we have created. We will deploy it to a new directory AcmeWeb in the Deploy directory for Chapter 14.
Bring up the Copy Project dialog from the menu Project | Copy Project....
Enter the following information (see Figure 1423).
Figure 14-23 Copying Web project files using Visual Studio.
http://localhost/Chap14/Deploy/AcmeWeb for Destination project folder
File share for Web access method
\OI\NetVb\Chap14\Deploy\AcmeWeb for Path
"Only files needed to run this application" for Copy
You can test the deployment by using Internet Explorer. Enter the following URL: http://localhost/Chap14/Deploy/AcmeWeb/WebForm1.aspx. You should then see the hotel information Web page displayed, and you should be able to select a city from the City dropdown and see the corresponding hotels displayed in the Hotel dropdown.
PRECOMPILED WEB PAGE
Examining the files in the folder Deploy\AcmeWeb, you will see no code-behind file WebForm1.aspx.vb. Instead, in the bin folder you will see the DLL AcmeWeb.dll.
INHERITS ATTRIBUTE IN PAGE DIRECTIVE
Examining the file WebForm1.aspx, we see there is no Src attribute. Instead, the Inherits attribute specifies the Page class WebForm1, which is implemented in the assembly AcmeWeb.dll.
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="AcmeWeb.WebForm1"%>
CONFIGURING A VIRTUAL DIRECTORY AS AN APPLICATION
The identical files you copied to Deploy\AcmeWeb are also provided in the directory AcmeRun. Try the URL http://localhost/Chap14/AcmeRun/ WebForm1.aspx in Internet Explorer. You will obtain a configuration error, as illustrated in Figure 1424.
Figure 14-24 Error message when virtual directory is not configured as an application.
The key sentence in the error message is "This error can be caused by a virtual directory not being configured as an application in IIS." The remedy is simple. Use Internet Services Manager to perform the following steps.
Find the folder AcmeRun in the virtual directory Chap14.
Right-click and choose properties. See Figure 1425. Click Create.
Figure 14-25 Configuring a virtual directory as an application inIIS.
Accept all the suggested settings and click OK.
Now again try http://localhost/Chap14/AcmeRun/WebForm1.aspx in Internet Explorer. You should be successful in bringing up the application.
MOVING A VISUAL STUDIO ASP.NET WEB APPLICATION PROJECT
Sometimes you will need to move an entire ASP.NET Web Application project so that you can continue development under Visual Studio. The simplest way to do this is to use the Visual Studio menu command Project | Copy Project. In the Copy Project dialog, select "All project files" for the Copy option. You will then enter the Destination project folder and the Path, as you did in deploying a Web application project. You will also need to edit the .vbproj.webinfo file to specify a correct URL path.
As an example, let's copy the AcmeWeb project we have been working on in the Demos directory, saving our current work in a new folder, AcmeWeb0 in the Demos directory.
Perform Copy | Copy Project, as described above. For Destination project folder enter http://localhost/Chap14/Demos/AcmeWeb0. Use File share as the Web access method. Enter C:\OI\NetVb\Chap14\ Demos\AcmeWeb0 for the Path.
Edit the file AcmeWeb.vbproj.webinfo to rename Web URLPath to: "http://localhost/Chap14/Demos/AcmeWeb0/AcmeWeb.vbproj"
Double-click on the file AcmeWeb.vbproj. This should bring up Visual Studio and create a new solution with a project AcmeWeb.
Build the solution. When presented with a Save As dialog, save the solution by the suggested name AcmeWeb.sln. You should get a clean build.
Try to run the project. You will be asked to set a start page. Set the start page as WebForm1.aspx.
Build and run. If you get a configuration error, use Internet Services Manager to configure the virtual directory as an application in IIS, as previously discussed. You should now be able to run the application at its new location.
You can view what we have done as establishing a snapshot of Step0. You can go back to new development in the main directory Demos\AcmeWeb, and if you want to compare with the original version, you have Demos\AcmeWeb0 available.