Web Applications Using Visual Studio.NET

for RuBoard

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

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 copy of the GUI application from Chapter 6, AcmeGui . The Hotel.dll component we need in the following demonstration is in the folder AcmeGui\Hotel\bin\Debug .

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 CaseStudy\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 10-17.

Figure 10-17. Configuring Web server connection preferred access method.

graphics/10fig17.gif

Creating an ASP.NET Web Application
  1. In Visual Studio select the menu File New Project.

  2. In the New Project dialog box choose "Visual C# Projects" as the Project Type and "ASP.NET Web Application" as the Template.

  3. Enter "AcmeWeb" as the name of your project. For the location enter an HTTP path to a folder on your server machine. The default will be the IIS home directory \Inetpub\ wwwroot . If you have made \OI\NetCs\Chap10 into a virtual directory with alias "NetCs", you can enter for the path http://localhost/NetCs/Demos , as illustrated in Figure 10-18.

    Figure 10-18. Creating a Visual Studio ASP.NET Web Application project.

    graphics/10fig18.gif

  4. Click OK. The project files will then be created in \OI\NetCs\ Chap10\Demos . The VS.NET solution AcmeWeb.sln will then be created under MyDocuments\Visual Studio Projects\AcmeWeb .

Using the Form Designer
  1. Bring up the Toolbox from the View menu, if not already showing. Make sure the Web Forms tab is selected.

  2. Drag two Label controls and two DropDownList controls onto the form.

  3. Change the Text property of the Labels to "City" and "Hotel." Resize the DropDownList controls to look as shown in Figure 10-19.

    Figure 10-19. Using the Form Designer to add controls to the form.

    graphics/10fig19.gif

  4. Change the (ID) of the DropDownList controls to listCities and listHotels.

Initializing the HotelBroker
  1. Copy Hotel.dll from AcmeGui\Hotel\bin\Debug to Demos\ AcmeWeb\bin .

  2. In your AcmeWeb , project add a reference to Hotel.dll .

  3. 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 graphics/icon17.gif to show the code.)

     using OI.NetCs.Acme; 
  4. Add a public static variable hotelBroker of type HotelBroker .

  5. Add code to Application_Start to instantiate HotelBroker .

     // Global.asax  using System;   using System.Collections;  using System.ComponentModel;  using System.Web;  using System.Web.SessionState;  using OI.NetCs.Acme;  namespace AcmeWeb  {     /// <summary>     /// Summary description for Global.     /// </summary>     public class Global : System.Web.HttpApplication     {  public static HotelBroker hotelBroker;  protected void Application_Start(Object sender,                                         EventArgs e)        {  hotelBroker = new HotelBroker();  }        ... 
  6. In WebForm1.aspx.cs add a using OI.NetCs.Acme; statement, and declare a static variable hotelBroker of type HotelBroker .

 ...  using OI.NetCs.Acme;  namespace AcmeWeb  {     /// <summary>     /// Summary description for WebForm1.     /// </summary>     public class WebForm1 : System.Web.UI.Page     {        ...  private static HotelBroker hotelBroker;  ... 
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 void Page_Load(object sender, System.EventArgs e)  {  if (!IsPostBack)   {   hotelBroker = Global.hotelBroker;   ArrayList cities = hotelBroker.GetCities();   listCities.DataSource = cities;   DataBind();   }  } 

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 10-20 shows the running application. When you drop down the list of cities, you will indeed see the cities returned by the HotelBroker component.

Figure 10-20. Running the Web page to show information about cities.

graphics/10fig20.gif

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 void Page_Load(object sender, System.EventArgs e)  {     if (!IsPostBack)     {        hotelBroker = Global.hotelBroker;        ArrayList cities = hotelBroker.GetCities();        listCities.DataSource = cities;  ArrayList hotels =   hotelBroker.GetHotels((string)cities[0]);   BindHotels(hotels);  DataBind();     }  }  private void BindHotels(ArrayList hotels)   {   ArrayList hotelNames = new ArrayList(hotels.Count);   foreach(HotelListItem hotel in hotels)   {   hotelNames.Add(hotel.HotelName.Trim());   }   listHotels.DataSource = hotelNames;   }  
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. The is a shortcut for adding a handler for the primary event for the control. In the Properties window you can click on the graphics/icon01.gif button to see all the events for the control. You can then double-click on the event. The second method allows you to add a handler for any event of the control. Here is the code for the SelectedIndexChanged event.

 private void listCities_SelectedIndexChanged(object  sender,     System.EventArgs e)  {     string city = listCities.SelectedItem.Text;     ArrayList hotels = hotelBroker.GetHotels(city);     BindHotels(hotels);     DataBind();  } 

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 AutoPostBack property to true . (You can get back to a display of properties from a display of events by clicking the graphics/icon13.gif button.) Figure 10-21 illustrates setting the AutoPostBack property.

Figure 10-21. Setting the AutoPostBack property of a DropDownList control.

graphics/10fig21.gif

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 graphics/icon16.gif ).

As an example, set a breakpoint on the first line of the SelectedIndexChanged event handler for listCities . Assuming you have set the AutoPostBack property to true , as we have discussed, you should hit the breakpoint, as illustrated in Figure 10-22.

Figure 10-22. Debugging a code-behind file in Visual Studio.

graphics/10fig22.gif

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. [4]

[4] This part of the Visual Studio development environment has been the most problematical in working with beta software. A technique we have found useful in the beta is to edit the .csproj.webinfo file to provide an HTTP path to a new location where the project has been moved. Then double-clicking on the .csproj file will create a new Visual Studio solution, which you can work with. Be sure to consult the readme.txt file for this chapter in the code distribution.

  1. The Project Copy Project... menu can be used to deploy a Web project from Visual Studio.

  2. Visual Studio precompiles Web pages, storing the executable in the bin folder.

  3. The Src attribute in the Page directive is not used. Instead, the Inherits attribute is used to specify the Page class.

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

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 AcmeWeb0 in the Deploy directory for Chapter 10.

  1. Using Windows Explorer, create a new directory AcmeWeb0 underneath Deploy .

  2. Bring up the Copy Project dialog from the menu Project Copy Project.

  3. Enter the following information (see Figure 10-23).

    • http://localhost/NetCs/Deploy/AcmeWeb0 for Destination project folder

    • File share for Web access method

    • \OI\NetCs\Chap10\Deploy\AcmeWeb0 for Path

    • "Only files needed to run this application" for Copy

    Figure 10-23. Copying Web project files using Visual Studio.

    graphics/10fig23.gif

  4. You can test the deployment by using Internet Explorer. Enter the following URL: http://localhost/netcs/deploy/AcmeWeb0/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\AcmeWeb0 , you will see no code-behind file WebForm1.aspx.cs . 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="c#" Codebehind="WebForm1.aspx.cs"  AutoEventWireup="false"  Inherits="AcmeWeb.WebForm1"  %> 
Configuring a Virtual Directory as an Application

The identical files you copied to Deploy\AcmeWeb0 are also provided in the directory AcmeRun\Step0 . Try the URL http://localhost/ netcs/AcmeRun/Step0/WebForm1.aspx in Internet Explorer. You will obtain a configuration error, as illustrated in Figure 10-24.

Figure 10-24. Error message when virtual directory is not configured as an application.

graphics/10fig24.gif

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.

  1. Find the folder Step0 underneath AcmeRun in the virtual directory NetCs .

  2. Right-click and choose properties. See Figure 10-25. Click "Create."

    Figure 10-25. Configuring a virtual directory as an application in IIS.

    graphics/10fig25.gif

  3. You will then see "Step0" suggested as the application name. Accept all the suggested settings and click OK.

  4. Now again try http://localhost/netcs/AcmeRun/Step0/ WebForm1.aspx in Internet Explorer. You should be successful in bringing up the application.

Moving a Visual Studio ASP.NET Web Application Project

At the time of writing there appeared to be no really clean way to move an entire ASP.NET Web Application project so that you could continue development under Visual Studio. The simplest approach we have found involves copying the source and bin files and editing the .csproj.webinfo file. A "brute force" approach is outlined in the readme.txt file for this chapter.

Our illustration will create a copy of the AcmeWeb Web application that we have been creating in the Demos directory. Our copy will be in a directory called AcmeWeb0 on the same machine. [5]

[5] The detailed steps outlined worked on Beta 2. Please consult the readme.txt file for this chapter to check for any changes in behavior in the released product.

  1. In Windows Explorer create a new folder AcmeWeb0 in the Demos directory.

  2. Close Visual Studio and copy all the source files, except the .sln and .suo files, from the AcmeWeb directory to AcmeWeb0 . Copy the whole bin folder.

  3. Edit the file AcmeWeb.csproj.webinfo to rename Web URLPath to:

    "http://localhost/NetCs/Demos/AcmeWeb0/AcmeWeb.csproj"

  4. Double-click on the file AcmeWeb.csproj . This should bring up Visual Studio and create a new solution with a project AcmeWeb .

  5. Remove the (broken) reference to Hotel and add this reference back in, navigating to bin\Hotel.dll .

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

  7. Try to run the project. You will be asked to set a start page. Set the start page as WebForm1.aspx .

  8. 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 Demo\AcmeWeb , and if you want to compare with the original version, you have Demo\AcmeWeb0 available.

for RuBoard


Application Development Using C# and .NET
Application Development Using C# and .NET
ISBN: 013093383X
EAN: 2147483647
Year: 2001
Pages: 158

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net