Programming Microsoft .NET

From Programming Microsoft .NET. Copyright 2002, Jeff Prosise. Reproduced by permission of Microsoft Press. All rights reserved.

Authors note: The following is extracted from the book Programming Microsoft .NET by Jeff Prosise (Microsoft Press, 2002, ISBN: 0-7356-1376-1) The book teaches readers how to take advantage of the .NET Framework. It covers the key programming models embodied in the .NET Framework, including Windows forms, Web forms, and XML Web services.


Web Forms and Visual Studio .NET

Editor's Note: This article continues Chapter 5, "Web Forms." The previous parts are:

Web Forms and Visual Studio .NET

Now that you know what makes Web forms tick, it's time to learn to build Web forms the Visual Studio .NET way. Visual Studio .NET brings rapid application development to the Web. You design forms by choosing controls from a palette and dropping them onto forms. You write event handlers by double-clicking controls and filling in empty method bodies. And you compile and run your application by executing simple menu commands. It's no accident that building Web forms with Visual Studio .NET feels a lot like building Windows applications with Visual Basic. That's exactly the feel Microsoft intended to convey.

This chapter closes with a step-by-step tutorial describing how to build a Web-based mortgage payment calculator with Visual Studio .NET. Figure 5-16 shows the finished product. Enter a loan amount, interest rate, and term (length of the loan in months), and click the Compute Payment button. The corresponding monthly payment appears at the bottom of the page.



Click here for larger image

Figure 5-16. Web-based mortgage payment calculator.

Step 1: Create a Virtual Directory

When you create a Web application project with Visual Studio .NET, you don't tell Visual Studio .NET where to the store the files by entering a path name; you enter a URL. Assuming you want to store the files on your PC but don't want to clutter \Inetpub\wwwroot with project subdirectories, your first step is to create a project directory and turn it into a virtual directory so that it's URL-addressable. Here are the steps:

  1. 1. Create a folder named Projects somewhere on your hard disk to hold your Web application projects. Then create a Projects subdirectory named LoanCalc.

  2. Start the Internet Information Services applet in Windows. You'll find it under All Programs/Administrative Tools.

  3. In the left pane of the Internet Information Services window, expand the Local Computer\Web Sites folder, and select Default Web Site.

  4. Select the New/Virtual Directory command from the Action menu to start the Virtual Directory Creation Wizard.

  5. When the wizard asks for an alias, type "LoanCalc." When it asks for a path name, enter the path to the LoanCalc directory you created in step 1. Click the Next and Finish buttons until the wizard closes.

You just created a physical directory named LoanCalc and converted it into a virtual directory. It's URL is http://localhost/loancalc. Before proceeding, verify that LoanCalc appears with the other virtual directories listed under Default Web Site in the Internet Information Services window, as shown in Figure 5-17.



Click here for larger image

Figure 5-17. Internet Information Services window.

Step 2: Create a Web Application Project

Start Visual Studio .NET, and then select the File/New/Project command. Fill in the New Project dialog exactly as shown in Figure 5-18. Verify that the statement "Project will be created at http://localhost/LoanCalc" appears near the bottom of the dialog. Then click OK to create a new project named LoanCalc in the LoanCalc directory you created a moment ago.



Click here for larger image

Figure 5-18. Creating the LoanCalc project.

Step 3: Change to Flow Layout Mode

The next screen you see is the Visual Studio .NET Web forms designer. Here you design forms by dragging and dropping controls. Before you begin, however, you have a decision to make.

The forms designer supports two layout modes: grid layout and flow layout. Grid layout mode lets you place controls anywhere in a form. It relies on CSS-P (Cascading Style Sheets-Position) to achieve precise positioning of controls and other HTML elements. Flow layout mode eschews CSS-P and relies on the normal rules of HTML layout. Flow layout mode is more restrictive, but it's compatible with all contemporary browsers.

So that LoanCalc will be compatible with as wide a range of browsers as possible, go to Visual Studio .NET's Properties window and change to flow layout mode by changing the document's pageLayout property from GridLayout, which is the default, to FlowLayout. Note that "DOCUMENT" must be selected in the combo box at the top of the Properties window for the pageLayout property to appear.

Before proceeding, click the form and select the Snap To Grid command from Visual Studio .NET's Format menu. This setting will make it easier to size and position the form's controls consistently with respect to one another.

Step 4: Add a Table

Since you're working in flow layout mode, tables are your best friend when it comes to positioning and aligning controls on a page. Click the Web form design window to set the focus to the designer. Then use Visual Studio .NET's Table/Insert/Table command to add an HTML table to the Web form. When the Insert Table dialog appears, fill it in as shown in Figure 5-19. In particular, set Rows to 4, Columns to 8, Width to 100 percent, Border size to 0, and Cell padding to 8. When you click OK, the table appears in the forms designer window.



Click here for larger image

Figure 5-19. Adding a table to a Web form.

Step 5: Insert Text

Click the cell in the table's upper left corner. A caret appears signaling that any text you type will appear inside the table cell. Type "Principal." Then go to the Properties window and change the cell's align property to "right" to right align the text. Repeat the process to add "Rate (percent)" to the cell in the next row, and "Term (months)" to the cell below that. Figure 5-20 shows how the table should look when you've finished.



Click here for larger image

Figure 5-20. The LoanCalc form after adding text.

Step 6: Add TextBox Controls

If the Toolbox window isn't displayed somewhere in the Visual Studio .NET window (it appears at the far left by default), choose the Toolbox command from the View menu to display it. Click the Toolbox's Web Forms button to display a list of Web controls, and then use drag-and-drop to add TextBox controls to the right-hand cells in the table's first three rows. (See Figure 5-21.) Finish up by using the Properties window to change the TextBox controls' IDs to "Principal," "Rate," and "Term," respectively.



Click here for larger image

Figure 5-21. The LoanCalc form after adding TextBox controls.

Step 7: Add a Button Control

Add a Button control to the rightmost cell in the table's bottom row, as shown in Figure 5-22. Size the button so that its width equals that of the text box above it. Change the button text to "Compute Payment" and the button ID to "PaymentButton."



Click here for larger image

Figure 5-22. The LoanCalc form after adding a Button control.

Step 8: Add a Label Control

Select a Label control from the Toolbox, and add it to the form just below the table, as shown in Figure 5-23. Change the Label control's text to an empty string and its ID to "Output."



Click here for larger image

Figure 5-23. The LoanCalc form after adding a Label control.

Step 9: Edit the HTML

The next step is to dress up the form by adding a few HTML elements. Start by clicking the HTML button at the bottom of the designer window to view the HTML generated for this Web form. Manually add the following statements between the <body> tag and the <form> tag:

<h1>
  Mortgage Payment Calculator
</h1>
<hr>

Next scroll to the bottom of the file and add these statements between the </table> tag and the <asp:Label> tag:

<br>
<hr>
<br>
<h3>

Finish up by inserting an </h3> tag after the </asp:Label> tag. Then click the Design button at the bottom of the forms designer to switch out of HTML view and back to design view. Figure 5-24 shows how the modified form should look.



Click here for larger image

Figure 5-24. The LoanCalc form after adding HTML tags.

Step 10: Add a Click Handler

Double-click the form's "Compute Payment" button. Visual Studio .NET responds by adding a method named PaymentButton_Click to WebForm1.aspx.cs and showing the method in the program editor. Add the following code to the empty method body:

try {
  double principal = Convert.ToDouble (Principal.Text);
  double rate = Convert.ToDouble (Rate.Text) / 100;
  double term = Convert.ToDouble (Term.Text);
  double tmp = System.Math.Pow (1 + (rate / 12), term);
  double payment =
     principal * (((rate / 12) * tmp) / (tmp - 1));
  Output.Text =
     "Monthly Payment = " + payment.ToString ("c");
}
catch (Exception) {
    Output.Text = "Error";
}

PaymentButton_Click isn't an ordinary method; it's an event handler. Check out the InitializeComponent method that Visual Studio .NET wrote into WebForm1.aspx.cs and you'll find a statement that registers PaymentButton_Click to be called in response to the Compute Payment button's Click events. InitializeComponent is called by OnInit. The handler that you just implemented responds to Click events by extracting user input from the form's TextBox controls, computing the corresponding monthly payment, and displaying the result in the Label control.

Step 11: Build and Test

You're now ready to try out your handiwork. Select Build from the Build menu to compile your code. If it builds without errors, choose Start (or Start Without Debugging) from the Debug menu to run it. When the Web form pops up in Internet Explorer, verify that it works properly by entering the following three inputs:

  • Principal: 100000

  • Rate: 10

  • Term: 240

Now click the Compute Payment button. If "Monthly Payment = $965.02" appears at the bottom of the page, give yourself a pat on the back. You just built your first Web form with Visual Studio .NET.

The LoanCalc Source Code

Of the many files in the LoanCalc directory, WebForm1.aspx and WebForm1.aspx.cs are the two that interest us the most. They contain LoanCalc's source code. (If you're curious to know what all those other files are for, be patient. You'll learn about many of them-particularly Global.asax and Web.config-in Chapter 9. Most of the extra files are superfluous in this example, but Visual Studio .NET insists on creating them anyway.) WebForm1.aspx contains no code; only HTML. Visual Studio .NET always uses code-behind in its Web forms, so all the C# code is located in WebForm1.aspx.cs. Figure 5-26 shows the finished versions of both files. Most of the content that you see was generated by Visual Studio .NET. The statements that you added are shown in boldface type.

Given what you already know about Web forms, there isn't much in LoanCalc's source code to write home about. The ASPX file defines the user interface using a mixture of HTML and Web controls, and the CS file contains the Compute Payment button's Click handler as well as the code that connects the button to the handler. Neither file contains anything you couldn't have written by hand, but it should be apparent that building Web forms visually is faster and less error prone than building them manually.


WebForm1.aspx
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" 
  AutoEventWireup="false" Inherits="LoanCalc.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
  <HEAD>
    <title>WebForm1</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" 
      content="http://schemas.microsoft.com/intellisense/ie5">
  </HEAD>
  <body>
    <h1>
      Mortgage Payment Calculator
    </h1>
    <hr>
    <form id="Form1" method="post" runat="server">
      <TABLE id="Table1" cellSpacing="1" cellPadding="8" 
        width="100%" bgColor="thistle" border="0">
        <TR>
          <TD align="right">
            Principal
          </TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD>
            <asp:TextBox id="Principal" runat="server"></asp:TextBox>
          </TD>
        </TR>
        <TR>
          <TD align="right">
            Rate (percent)
          </TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD>
            <asp:TextBox id="Rate" runat="server"></asp:TextBox>
          </TD>
        </TR>
        <TR>
          <TD align="right">
            Term (months)
          </TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD>
            <asp:TextBox id="Term" runat="server"></asp:TextBox>
          </TD>
        </TR>
        <TR>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD></TD>
          <TD>
            <asp:Button id="PaymentButton" runat="server" 
              Text="Compute Payment" Width="157px"></asp:Button>
          </TD>
        </TR>
      </TABLE>
      <br>
      <hr>
      <br>
      <h3>
        <asp:Label id="Output" runat="server"></asp:Label>
      </h3>
    </form>
  </body>
</HTML>

WebForm1.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace LoanCalc
{
  /// <summary>
  /// Summary description for WebForm1.
  /// </summary>
  public class WebForm1 : System.Web.UI.Page
  {
    protected System.Web.UI.WebControls.TextBox Principal;
    protected System.Web.UI.WebControls.TextBox Rate;
    protected System.Web.UI.WebControls.Button PaymentButton;
    protected System.Web.UI.WebControls.Label Output;
    protected System.Web.UI.WebControls.TextBox Term;

    private void Page_Load(object sender, System.EventArgs e)
    {
      // Put user code to initialize the page here
    }

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
     //
     // CODEGEN: This call is required by the ASP.NET 
     // Web Form Designer.
     //
      InitializeComponent();
     base.OnInit(e);
  }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {    
      this.PaymentButton.Click +=
        new System.EventHandler(this.PaymentButton_Click);
      this.Load += new System.EventHandler(this.Page_Load);

    }
    #endregion

    private void PaymentButton_Click(object sender,
    System.EventArgs e)
    {
      try {
        double principal = Convert.ToDouble (Principal.Text);
        double rate = Convert.ToDouble (Rate.Text) / 100;
        double term = Convert.ToDouble (Term.Text);
        double tmp = System.Math.Pow (1 + (rate / 12), term);
        double payment =
          principal * (((rate / 12) * tmp) / (tmp - 1));
        Output.Text =
          "Monthly Payment = " + payment.ToString ("c");
      }
      catch (Exception) {
        Output.Text = "Error";
      }
    }
  }
}
Figure 5-26. The LoanCalc source code.

A Glimpse into the Future

A lot of developers-not all of them Microsoft employees-believe that Web forms are a glimpse at the future of Web programming. The idea of encapsulating complex rendering and behavioral logic in reusable control classes and having those controls fire events that can be processed on Web servers is one whose time has come. Server controls provide the building blocks for sophisticated Web forms while shielding the developer from the nuances of HTML and client-side scripting. That's a win no matter how you look at it (or which computer company-Sun or Microsoft-you swear allegiance to).

You now know more about Web forms than 99.999 percent of the people on the planet. But there's still much to learn. In the next chapter, you'll continue the journey to Web Forms enlightenment by learning about all the different controls in System.Web.UI.WebControls. After that, you'll learn how to build Web controls of your own, structure applications around Web forms, create secure Web forms, and much more. Most importantly, you'll discover that putting your software on the Web isn't such a scary proposition after all.


Editor's Note: This completes the excerpt of Chapter 5 from Jeff Prosise's book, Programming Microsoft .NET.

About the Author

Jeff Prosise makes his living programming Microsoft .NET and teaching others how to do the same. A former engineer who discovered after college that programming is immeasurably more fun than designing lifting fixtures and computing loads on mounting brackets, today Jeff travels the world for Wintellect, the company he co-founded in 2000, helping other companies get up to speed on Microsoft .NET. Programming Microsoft .NET is Jeff's ninth book.

Programming Microsoft .NET. Copyright 2002, Jeff Prosise. Reproduced by permission of Microsoft Press. All rights reserved.

# # #



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • CentreCorp is a fully integrated and diversified property management and real estate service company, specializing in the "shopping center" segment, and is one of the premier retail service providers in North America. Company executives travel a great deal, carrying a number of traveling laptops with critical current business data, and no easy way to back up to the network outside the office. Read this case study to learn how CentreCorp implemented a suite of business continuity services that included …

Most Popular Programming Stories

More for Developers

RSS Feeds