A Visual Basic Developer's Introduction to ASP.NET 2.0

 

Scott Swigart

August 2006

Applies to:
   ASP.NET 2.0
   Visual Studio 2005

Summary: This article provides Visual Basic .NET and Visual Basic 6 developers with an introduction to building Web applications with ASP.NET 2.0. It focuses on the major differences between developing desktop applications and Web applications. (10 printed pages)

Contents

Introduction
Getting Started
Page Layout
Event Driven-ish
Managing State
Data-Centric Sites
Other Important ASP.NET 2.0 Features
Conclusion
Additional Resources

Introduction

If you are at all like me, you primarily develop desktop applications. However, it is quite common that desktop developers need to do Web development from time to time. The purpose of this article is to quickly get Visual Basic .NET and Visual Basic 6 developers up-to-speed on building Web applications with ASP.NET 2.0. As such, this article endeavors to speak the language of desktop developers, and it focuses on what is different about developing for the Web. This article also assumes that your primary objective is to build Web pages over data, and that you will be most interested in allowing the user to display information from a database. Does this describe you? Then read on.

Getting Started

To follow the steps in this article, you will need Visual Studio 2005. You will also need to download the Visual Studio 2005 Web Application Projects add-in. For walkthroughs that display information from the database, you will also need SQL Server 2005 Express Edition and the Northwind sample database.

Visual Studio 2005 provides the capabilities to build full-featured ASP.NET Web sites. However, Visual Studio 2005 originally shipped with a project-less system for building Web sites. For someone coming from a desktop development background, this made building Web sites work and feel much different from building desktop applications. The Visual Studio 2005 Web Application Projects add-in increases the similarity between building Web sites and desktop applications. The walkthroughs in this article assume that you have this add-in installed.

Walkthrough: Creating a simple Web application

  1. If you have not already done so, download and install the Visual Studio 2005 Web Application Projects add-in.

  2. Start Visual Studio 2005.

  3. On the File menu, click New, and then click Project.

  4. For Project Type, select Visual Basic.

  5. For Template, select ASP.NET Web Application.

    Visual Studio will create the new Web application that contains a single Web page. The designer will show you the markup code for the page. You can edit the page in this Source view, or you can use a WYSIWYG editor.

       

    Click here for larger image

    Figure 1. New Web application (Click on the image for a larger picture)

  6. Click the Design button at the bottom of the code editor to switch to WYSIWYG view.

    At first glance, building Web applications can be deceptively similar to building desktop applications.

  7. Click on the design surface, and type Enter your name: .

  8. From the Toolbox, drag a Textbox control onto the design surface, directly after the text that you just entered.

  9. Click to place the cursor after the Textbox control, and press ENTER to create a new line.

  10. From the Toolbox, drag a Button control onto the design surface.

  11. Click to place the cursor after the Button control, and press ENTER to create another line break.

  12. From the Toolbox, drag a Label control onto the design surface, below the button.

    The completed page should appear as shown in Figure 2.

    Aa730833.avbdvlper02(en-US,VS.80).gif

    Figure 2. Web application with controls

Page Layout

One thing should be quickly apparent when you start building Web pages; you cannot just put a control anywhere you feel like. Desktop applications are designed to allow you to position controls at any pixel location you desire. Web pages, on the other hand, are designed to "flow." This means that the layout of your page will be dynamically formatted. The browser will make lines longer if more space is available, and it will wrap lines if less space is available.

This also means that the laying out of labels and text boxes requires that your Web controls be placed in tables that control alignment.

Walkthrough: Laying out controls

  1. Select the content of the page, and press DELETE to erase everything.

  2. On the Layout menu, click Insert Table.

  3. For Rows, enter 2.

  4. For Columns, enter 2.

  5. Click OK.

    You can type or drag controls directly into the cells of the table. Notice that the table ensures that the left edges of your text boxes all align nicely. Tables are the primary mechanism for controlling the layout of Web pages.

  6. By typing in the table cells and dragging controls from the Toolbox, create the user interface shown in Figure 3.

    Aa730833.avbdvlper03(en-US,VS.80).gif

    Figure 3. Web application using tables to control layout

Event Driven-ish

ASP.NET provides a programming model that feels a lot like building Windows Forms applications. For simple scenarios, the "Web" nature of the application is abstracted away, and you are able to leverage your desktop developer experience to get started quickly.

Walkthrough: Hooking up event handlers

  1. Double-click the Button control on the design surface to generate the code for its Click event.

  2. Enter the following code.

    Label1.Text = "Welcome " & TextBox1.Text
    

  3. Press F5 to "run" the Web application.

  4. Type your name in the User Name text box.

  5. Click the Button button. You should see something similar to Figure 4.

    Aa730833.avbdvlper04(en-US,VS.80).gif

    Figure 4. Testing the event handlers

This seems logical enough, but it is important to understand what is happening here. Code runs on the Web server to generate the HTML page, which is sent to, and displayed, in the browser. If this were a Windows application, the Form containing the controls would still be running, and it could contain variables, and so on. However, with Web applications, by the time you see the user interface in the browser, the page class on the server has been unloaded.

Managing State

Imagine building a desktop application where the application had to shut down and restart between every user interaction. In other words, the application would generate a Form that the user could see, and then the executable would terminate. When the user clicked a button on the form, the application would quietly restart, process the input, generate a new Form bitmap, and then shut down. The results would be a very forgetful application. Any data that you did not code to be saved on shutdown and loaded on startup would be lost. Form-level variables would be effectively useless, because their values would be lost between shutdown and startup. As odd as this sounds, it is essentially how Web applications work. The following walkthrough will illustrate this behavior.

  1. In Visual Studio 2005, in the Solution Explorer, right-click Default.aspx, and then click View Code.

  2. On a line after Inherits System.Web.UI.Page, enter the following code.

    Public previousUser As String
    

    This is a page-level variable that will store the previous user name that you entered.

  3. Modify the code for the Button1_Click event handler as follows.

    Label1.Text = "You were " & previousUser & ", and now you're " & TextBox1.Text
    previousUser = TextBox1.Text
    

    If you run the application, enter the name Fred, click the button, and then enter the name Jim and click the button again, you would expect to see the message You were Fred, and now you're Jim. This is the way this code would work in a desktop application. However, you will see that this is not the behavior that you get.

  4. Press F5 to run the application.

  5. Enter Fred and click the button.

  6. Enter Jim and click the button.

    Notice that the previousUser value is never showing up. It is always saying You were , and now you're Jim. What is going on?

    The problem is that the page class is being destroyed and recreated on every button click. This means that previousUser gets created and initialized to an empty string, it is then assigned the value from the text box, the page processing completes, the page class is destroyed, and the previousUser variable is just thrown away. When you click the button again, this process repeats.

    The page is not the place to store any information that the site needs to remember across user interactions. Instead, ASP.NET provides just such storage through "Session" variables.

  7. Modify the code for the Button1_Click event handler as follows.

    Label1.Text = "You were " & Session("previousUser") & ", and now you're " & TextBox1.Text
    Session("previousUser") = TextBox1.Text
    

  8. Press F5 to run the application.

  9. Enter Fred and click the button.

  10. Enter Jim and click the button.

    Now you are getting the correct behavior (see Figure 5). By using Session variables, the site is able to remember information across user interactions.

    Aa730833.avbdvlper05(en-US,VS.80).gif

    Figure 5. Using Session variables to manage state

Managing state is one of the biggest differences between Web and desktop development. If you need your Web site to remember anything across user interactions (and you typically do), you cannot use simple variables to store that information. Instead, you need to use something like Session variables to explicitly instruct the Web server to remember a value.

Data-Centric Sites

Most Web sites function primarily as a user interface on top of database information. ASP.NET 2.0 goes a long way toward simplifying these kinds of sites. The next walkthrough will give you a feel for what this is like. Note that building full data-centric sites is a big topic, and it cannot be covered completely in this article. That said, the Additional Resources section should point you toward many places where you can go to gain more knowledge.

To perform the following walkthrough, you will need to download and install SQL Express and the sample Northwind database. Links to these can be found in the Additional Resources section.

  1. In the Solution Explorer, on the Project menu, click Add New Item.

  2. For Template, select WebForm, and then click Add.

  3. Click the Design tab at the bottom of the code editor window.

  4. From the Data section of the Toolbox, drag a GridView control onto the designer.

  5. From the GridView Tasks smart tag, click Choose Data Source, and then click <New data source>.

  6. In the Choose a Data Source Type dialog box, select Database, and then click OK.

  7. Click New Connection.

  8. For Server Name, enter localhost if you have SQL Server installed. If you have SQL Express installed, enter .\sqlexpress.

  9. For Select or enter a database, enter Northwind.

  10. Click Test Connection to ensure that you can connect to the database.

  11. Click OK.

  12. Click Next.

    Information such as a connection string is not simply hard-coded into the application. Instead, this type of information is placed in the Web app.config file, where it can be easily changed without requiring source code changes. Here, you are prompted for the name to give the connection string.

  13. In the Save the Connection String dialog box, click Next.

    Next, you are prompted for the source of the data that you want to display. You can enter add-hoc SQL, use a stored procedure, or select a specific table or view.

  14. In the Name drop-down list, click Orders.

  15. For Columns, select *.

  16. Click Next.

  17. Click Test Query to ensure that communication with the database functions as expected.

  18. Click Finish.

    Notice that the GridView control shows the database columns at design time. You also have full control over how the grid is rendered. The standard Web way of applying a consistent look and feel to a Web site is through a technology known as Cascading Style Sheets. However, a simpler mechanism is to auto-format the grid, much like you would pick an auto-format in Microsoft Office.

  19. Right-click the GridView control, and then click Auto Format.

  20. Choose one of the formats, such as Professional.

    The GridView control also supports a number of advanced features, such as sorting and paging, with no coding required.

  21. Right-click the GridView control, and then click Properties.

  22. In the Properties Panel, set the AllowPaging property to True.

  23. Set the AllowSorting property to True.

  24. Press F5 to run the Web application.

  25. The application should appear as shown in Figure 6.

       

    Click here for larger image

    Figure 6. Data-centric Web application (Click on the image for a larger picture)

You can click column headings to sort on that column. You can click on the page numbers at the bottom to page through the results.

Other Important ASP.NET 2.0 Features

There are a number of other features in ASP.NET that greatly increase productivity, and that target common development scenarios.

Master Pages

With Desktop applications, it is easy to simply put the appropriate menus and toolbars on individual forms. With Web sites, however, the navigation is typically more global. A single navigation bar is often displayed on all pages of the site. ASP.NET provides the capability to do this through Master pages. You simply add a Master page as an item to your solution. You use tables on the Master page to control where the header, navigation bar, footer, main page content, and so on should go. Then, you have a particular content page reference the Master page. The page content will appear inside the Master page, in the content area. Figure 7 shows a simple example. For more information on using Master pages, see the Additional Resources section.

Click here for larger image

Figure 7. Master page (Click on the image for a larger picture)

Authentication and Authorization

It is very common to have a site, or portion of a site, that requires a user name and password in order to gain access. ASP.NET 2.0 provides extensive support for this scenario. First, ASP.NET gives you a site administration tool that includes a Wizard that will walk you through configuring sections of your site for membership (see Figure 8).

Click here for larger image

Figure 8. Security Setup Wizard (Click on the image for a larger picture)

For more information on Web site security, see the Additional Resources section.

Conclusion

Web development is different from Desktop development. However, the ASP.NET programming model provides a number of striking similarities. When building Web sites, you simply wire up event handlers for controls, just like you would do with desktop applications. Managing state is different, because pages are created and destroyed on each request, but ASP.NET does provide the Session variable to let you persist information in memory on the server. ASP.NET also includes simple-to-use yet powerful controls for common scenarios, such as building data-centric Web sites. Finally, ASP.NET includes full wizards to walk you through site configuration for complex tasks, such as enabling authentication and authorization.

Additional Resources

Prerequisites for This Article

Getting Started Without Visual Studio

  • Visual Web Developer 2005 is a free, small development environment that lets you get started with ASP.NET 2.0 development. If you do not have access to Visual Studio 2005, I strongly encourage you to check out Visual Web Developer.

Getting Help

Training Courses

  • Web E-Learning Courses are available from Microsoft at reasonable rates. If you are looking for self-directed in-depth training, you should look here.

Into the Future

  • Mix 06 Presentations take a look into the future of Web and desktop development. If you want to see what the technology is evolving toward, look here.

 

About the author

Scott Swigart spends his time consulting, authoring, and speaking about converging and emerging technologies. With development experience going back over 15 years, and by staying in constant contact with future software development technologies, Scott is able to help organizations get the most out of today's technology while preparing to leverage the technology of tomorrow. Scott is also the author of several .NET books, a certified Microsoft trainer (MCT) and developer (MCSD), and a Microsoft MVP. Feel free to contact Scott at scott@swigartconsulting.com, or check out his latest musings at blog.swigartconsulting.com.

© Microsoft Corporation. All rights reserved.