Home > Articles > Programming > ASP .NET

This chapter is from the book

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 14–17.

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

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 Basic Projects as the Project Type and ASP.NET Web Application as the Template.

  3. Enter http://localhost/Chap14/Demos/AcmeWeb as the location of your project, as illustrated in Figure 14–18. This setting assumes you have made \OI\NetVb\Chap14 into a virtual directory with alias Chap14.

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

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

  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 14–19.

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

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

INITIALIZING THE HOTELBROKER

  1. Copy Hotel.dll from AcmeGui 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 to show the code.)

  4. Imports OI.NetVb.Acme 
  5. Add a public shared variable broker of type HotelBroker.

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

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 14–20 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-20Figure 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 14–21. 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-21Figure 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 14–22 illustrates setting the AutoPostBack property. The program should now work properly. The project is saved in the folder AcmeWeb\Step0.

Figure 14-22Figure 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.

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

  1. Bring up the Copy Project dialog from the menu Project | Copy Project....

  2. Enter the following information (see Figure 14–23).

    Figure 14-23Figure 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

  3. 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 14–24.

Figure 14-24Figure 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.

  1. Find the folder AcmeRun in the virtual directory Chap14.

  2. Right-click and choose properties. See Figure 14–25. Click Create.

    Figure 14-25Figure 14-25 Configuring a virtual directory as an application inIIS.

  3. Accept all the suggested settings and click OK.

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

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

  2. Edit the file AcmeWeb.vbproj.webinfo to rename Web URLPath to: "http://localhost/Chap14/Demos/AcmeWeb0/AcmeWeb.vbproj"

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

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

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

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020