Beginning Object-Oriented Programming with C# (2012)
Part V
Advanced Topics
Chapter 18
Web Programming
What you will learn in this chapter:
· What a web page is and how it works
· The relationship between the client and web server
· The difference between static and dynamic web pages
· How to use C# with web pages
· How to write a simple dynamic web page
wrox.com code downloads for this chapter
You can find the wrox.com code downloads for this chapter at www.wrox.com/remtitle.cgi?isbn=9781118336922 on the Download Code tab. The code in the Chapter17 folder is individually named according to the names throughout the chapter.
This chapter discusses how to use C# for programming web applications. There is no way that you can do justice to web programming in a single chapter. Indeed, there are hundreds of books devoted to just web programming. Instead, the goal here is to give you background information so that you understand the paradigm involved with programming for the web. After that, if you want to become more involved with web programming, there are a number of Wrox publications that can help you master the web.
Before you begin programming your first Internet web page, you need to understand the basics of how web pages are written and displayed on your browser.
Static Web Pages
Whenever you load your web browser and it displays an Internet page, whatever you see displayed on the monitor was constructed from a Hypertext Markup Language (HTML) script. A static web page is a page whose content never changes. Because the content never changes, the page always looks the same regardless of who visits the page or how they happened to land on that particular page. The view of the page is static and unchanging.
In the following Try It Out, you use Visual Studio to write a simple static web page. Assume you've loaded Visual Studio and are ready to make a project selection.
Try It Out: Static Web Page [Chapter18ProgramStaticWebPage.zip]
Writing a static Web page is not difficult—just follow these steps:
1. From the Visual Studio menu, select File → New → Web Site → ASP.NET Empty Web Site. This presents the dialog shown in Figure 18.1. The Web Location should be named StaticWebPage.
Figure 18.1 Web selection
2. Having made your selection, type in StaticWebPage for the project file and click OK. Visual Studio gets busy doing some background things and eventually presents you with the IDE that looks like Figure 18.2.
Figure 18.2 Visual studio environment
3. Move to the Solution Explorer Window, and right-click the project's name (StaticWebPage). Then select the Add → Web Form that calls up a dialog that asks you to enter the name of the form. This process is shown in Figure 18.3, whereas Figure 18.4 shows the dialog box.
Figure 18.3 Add web form selection process
Figure 18.4 Web form name dialog
4. Accept the default name (that is, “Default”) and click OK. Visual Studio creates the file and displays the IDE, which now looks similar to Figure 18.5.
Figure 18.5 IDE after file selection
Notice that the Solution Explorer has added the Default.aspx file to your project. The .aspx file extension stands for Active Server Page Extended, and Default.aspx is now your static web page. (You could name the page Default.htm or Default.html and the same file could also be used as a web page.)
Replace that code you see in the Source Window with what you see in Listing 18-1.
Listing 18-1: The Default Web Page (default.aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>My First Web Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>This is a static web page</h1>
<br/>
Not much going on here…
</div>
</form>
</body>
</html>
Now run the program. Using whatever happens to be your default web browser, the output will look like that shown in Figure 18.6.
Figure 18.6 Static web page
Although this web page isn't much to look at, it can serve as a good starting point for a discussion about web pages.
How It Works
The first thing to notice is that the Source window has some new options presented at the bottom of the window, as shown in Figure 18.7.
Figure 18.7 Source Window options
The view you currently see on your display is the Source option, which displays the HTML code for the current web page. If you click on the Design option, the display changes and displays the current state of the page. In this example, the Design option looks like Figure 18.6. You can switch back and forth between these two windows to see the impact that your code changes in the Source window has on the way the page looks when it is displays. The Split option divides the Source window horizontally to enable you to see both the Source and Design windows at the same time. This saves you from having to click the option you want as you develop the page.
When you run the program (F5), the program looks like Figure 18.6. If you look closely, you can see that the URL address bar in the figure contains http://localhost:2245/Default.aspx.
The http means that you are using the Hypertext Transfer Protocol (HTTP) to exchange information between the server and the client. In this case, the term localhost:2245 specifies that your computer is going to host the Default.aspx web page. The.aspx file extension stands for Active Server Page Extended and simply identifies the file as an extension of the older.asp file type. (Fortunately, these are details that Visual Studio uses in the background so you don't need to be concerned about them.) Stated differently, the line tells you the web page that is displayed on your computer. Using the localhost identifier makes it easier to develop, test, and debug a web application because you don't need to deploy the modified web page to some server each time you need to test the program.
Now that you know what the program looks like when it is run, examine the code for the web page. You can ignore the first two lines in Listing 18-1. Now consider the line
<!DOCTYPE html>
This line is an HTML comment line. The markup for a comment is
<! Comment >
where <! starts the comment and the > ends the comment. Technically, an HTML comment starts with <!-- and ends with -->. If you change the comment to
<!-- DOCTYPE html -->
you can see that the font color changes to green to denote an HTML comment. If you run the program, there is no observable change in the program.
The next line
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
defines the namespace for the HTML version used in the page. This reference tells you that Visual Studio uses Extended HTML. The next line simply says that the page is to be run at the server, in your case, the localhost.
The remainder of the program deals with displaying the page as you wrote it. You could simplify the page as shown here, and the output would still look the same.
<html>
<head >
<title>My First Web Page</title>
</head>
<body>
<h1>This is a static web page</h1>
<br/>
Not much going on here…
</body>
</html>
Although it may appear that much of the HTML in Listing 18-1 is unnecessary, that isn't the case when you develop more complex web pages.
Most of the HTML directives come in pairs. That is, an h1 header style is introduced with
<h1>
and terminates with
</h1>
These directives are often referred to as HTML tags or simply tags. The break tag, <br /> doesn't require a pair of tags but still follows the convention of opening and closing brackets (<>).
The process to display a web page is shown in Figure 18.8. The user controlling the browser is called the client. (Technically, the browser is the client and it's the user who controls the browser. A browser is an application that can render HTML information on a display device.) The client requests a web page from the server (1). The system that stores the previously written HTML pages is called the server. When the client request comes in, the server locates the wanted web page (2) and then sends that page back to the browser (3). It is the responsibility of the browser to render the page on the browser for the client to view.
Figure 18.8 Process to display a web page
The server processing is limited to locating the proper page, and the processing on the client side is limited to the browser rendering the HTML page. The page does not change unless the client initiates some kind of request back to the server.
If you sit and watch the static web page for about one-half an hour, you can notice nothing changes. Static web pages are like that…they just sit there displaying the same content. Web browsing would be dull if all web pages were static. Fortunately, that's not the case. So now move on to see how dynamic web pages can liven things up a bit.
Dynamic Web Pages
Dynamic web pages have the capability to change their content. Visual Studio supports ASP.NET files that you can use on a dynamic web page. The web page you just created was a static web page but with the .aspx secondary file name. (As you learned earlier in this chapter, older ASP.NET files ended in.asp, whereas the extended pages have a secondary filename of.aspx. You use the .aspx files for the remainder of this chapter.)
ASP.NET files usually contain a blend of HTML script and ASP.NET tags. The ASP.NET tags enable you to mix in C# code with the HTML script to produce dynamic HTML pages. After the C# code executes, the results are reformatted into an HTML page that is then sent back to the browser for display.
Processing can be done on either the server or client side of the exchange. Most browsers, for example, have the capability to use JavaScript, Flash, and Silverlight code. Many servers can process code written in Java, Perl, ColdFusion, Python, Ruby, and ASP. If the server can process ASP.NET files, it has the capability to process pages with C#, Visual Basic, or C++ code. (They share a common intermediate language.) Although this duality exists, it seems clear that server-side processing wins the coin toss, especially in light of the advances in cloud computing. Sometimes this seems wasteful when I sit in front of my browser running on a computer with a quad-core CPU loafing along at 3Ghz, a megamunch of memory, a terabyte of storage but processing an HTML page that could be done in the blink of an eye by an 8080 CPU, not to mention the time wasted making the round trip to the server. Oh well.…
In the next Try It Out, you develop a simple web application that calculates the monthly payment for a mortgage loan. Using the Five Program Steps from Chapter 2, the Initialization step doesn't require anything special other than the standard web setup information. The Input step requires the amount of the loan, the interest rate, and the number of months the mortgage is active. The Process step requires an algorithm that takes the data from the Input step and yields a monthly payment amount. The Output step simply involves formatting the payment amount as an HTML page and sending it back to the client. The Termination step doesn't require anything special. With this in mind, you can start.
Try It Out: Mortgage Calculator [Chapter18ProgramSMortgageCalculator.zip]
The first thing you need to do is create a new project named MortgageCalculator. To do this, follow these steps:
1. Select new project using the File → New → Web Site and then select ASP.NET Empty Web Site (refer to Figure 18.1).
2. Give the new project the name MortgageCalculator.
3. In the Solution Explorer, right-click the project name, and use the Add → Add New and select Web Form from the dialog box, supplying the name Default.aspx (refer to Figure 18.4).
4. Select the Design tab at the bottom of the Source Window.
5. From the menu, select Format → Set Position → Absolute. This enables you to fix the location of the objects on the form.
6. Drag and drop four labels, four textboxes, and one button object onto the form. The user interface should look something like that shown in Figure 18.9.
Figure 18.9 Mortgage calculator user interface
7. Apply the following attributes to the objects' properties, as shown in Table 18.1.
Table 18.1 Interface Objects and Their Settings
The reason to write in values for the textbox objects is to make it easier when you run the program during testing and debugging. With the values shown, the monthly payment should be $970.12.
8. Click the Source tab at the bottom of the Source Window, and your code should look something like that shown in Listing 18-2.
Listing 18-2: Mortgage Calculator Page (Default.aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title/>
<style type="text/css">
.auto-style1
{
width: 951px;
}
.auto-style2
{
width: 951px;
height: 55px;
position: absolute;
left: 10px;
top: 15px;
}
.auto-style3
{
height: 55px;
}
.auto-style4
{
position: absolute;
}
.auto-style5
{
left: 10px;
}
.auto-style6
{
top: 15px;
}
</style>
</head>
<body>
<form id="form1" runat="server" style="z-index: 1">
<div class="auto-style2">
<h1>Mortgage Calculator</h1>
<asp:Label ID="Label1" runat="server" Font-Size="Medium"
style="z-index: 1; left: 18px; top: 78px; position: absolute;
width: 136px; right: 797px; text-align: right;"
Text="Amount of loan:"></asp:Label>
<asp:TextBox ID="txtAmount" runat="server"
style="z-index: 1; left: 165px; top: 77px; position:
absolute">164000</asp:TextBox>
<asp:Label ID="Label2" runat="server" Font-Size="Medium"
style="z-index: 1; left: 4px; top: 101px;
position: absolute; width: 148px; right: 799px;
text-align: right;" Text="Interest rate (6% = 6): ">
</asp:Label>
<asp:TextBox ID="txtInterestRate" runat="server"
style="z-index: 1; left: 165px; top: 99px; position: absolute"
TabIndex="1">5.875</asp:TextBox>
<asp:TextBox ID="txtMonths" runat="server"
style="z-index: 1; left: 165px; top: 121px; position: absolute"
TabIndex="2">360</asp:TextBox>
<asp:Button ID="btnSubmit" runat="server"
style="z-index: 1; left: 16px; top: 172px; position: absolute"
Text="Submit" TabIndex="3" OnClick="btnSubmit_Click"/> </div>
<p>
<asp:Label ID="lblPayment" runat="server" Font-Size="Medium"
style="z-index: 1; left: 27px; top: 232px; position: absolute; width:
136px; right: 811px; height: 18px; text-align: right;"
Text="Monthly payment:" Visible="False"></asp:Label>
</p>
<asp:Label ID="Label3" runat="server" Font-Size="Medium"
style="z-index: 1; left: 27px; top: 136px; position: absolute; width:
136px; right: 808px; height: 18px; text-align: right;"
Text="Months:"></asp:Label>
<asp:TextBox ID="txtPayment" runat="server"
style="z-index: 1; left: 165px; top: 227px; position: absolute"
Visible="False"></asp:TextBox>
</form>
</body>
</html>
If you have dragged and dropped the objects onto the web form, much of the code in Listing 18-2 has already been written for you by Visual Studio as you created the user interface. However, just cutting and pasting the code presented here is the easy way to do it.
9. Finally, double-click the Submit button, which opens the Default.aspx.cs and add the code shown in Listing 18-3. (Much of the stub code was automatically generated for you by Visual Studio.)
Listing 18-3: The Code Behind Source Code for Mortgage Calculator (Default.aspx.cs)
using System;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
bool flag;
decimal amount;
decimal interestRate;
decimal months;
decimal payment;
decimal temp;
flag = decimal.TryParse(txtAmount.Text, out amount);
if (flag == false)
payment = 0.0M; // Bad input
flag = decimal.TryParse(txtInterestRate.Text, out
interestRate);
if (flag == false)
payment = 0.0M; // Bad input
flag = decimal.TryParse(txtMonths.Text, out months);
if (flag == false)
payment = 0.0M; // Bad input
interestRate /= 1200; // Need it as decimal fraction by month
temp = (decimal) Math.Pow(1.0 + (double) interestRate,
(double)months);
payment = interestRate * amount * (temp / (temp - 1.0M));
StringBuilder myPayment = new StringBuilder();
myPayment.AppendFormat("${0:F2}", payment);
lblPayment.Visible = true;
txtPayment.Visible = true;
txtPayment.Text = myPayment.ToString();
}
}
The code in Listing 18-3 is often called the code-behind file because it is the C# code that processes the information and, hence, is the work horse “behind” the web page.
You can now run the program.
How It Works
After you create the project and start to add objects to the web form in the Design mode, Visual Studio starts generating code in accordance to your interaction with the form. For example, consider the following line from Listing 18-2.
<asp:Label ID="Label2" runat="server" Font-Size="Medium"
style="z-index: 1; left: 4px; top: 101px;
position: absolute; width: 148px; right: 799px;
text-align: right;" Text="Interest rate (6% = 6): ">
</asp:Label>
Because the name for this label object is not directly used in the code-behind file, the default name of Label2 is acceptable.
The runat="server" attribute means that the form and its related controls should be processed on the server and that the control can be accessed by server scripts. Most of the remainder of the line is concerned with the visible attributes of the object. In many cases, experienced programmers are so familiar with such code that they write the code faster themselves rather than dragging and dropping the objects.
In Listing 18-3, the btnSubmit_Click() event is triggered when the Submit button is clicked by the user of the web page. That method begins with several data definitions and then checks to see that the user supplied reasonable data via the TryParse() calls you've used before. Note how simple it is to add this code to the project. The information stored in the textboxes is actually on the client machine, but the processing is taking place on the server. The communication between the two is handled for you more or less automatically.
After the data is validated (this could be improved), the code calculates the appropriate monthly payment. Although you could use other means to format the answer, use a StringBuilder object to format the payment as a floating point number with two decimal points. (Notice the using System.Text reference.) The code then makes the result label and textbox visible and places the formatted result into the txtPayment textbox. The result is shown in Figure 18.10.
Figure 18.10 Web page with result
With the data supplied by the user, the monthly payment is $970.12.
Keep in mind what happened to make this simple program work when used on the web. First, the web page must be located when the user selects the page to use the mortgage calculator. That page is then sent back to users as an HTML document that displays on their browser.
Users then fill in the requested data and that data is sent back to the server. Because the page has ASP.NET tags in it, the server knows that the button click event in the code-behind file should be called for processing. This is known because of the
OnClick="btnSubmit_Click"
attribute in the Submit button's attribute list. This attribute tells the server which method to call when the user clicks the Submit button. After the C# code has done its job, the page is reformatted as an HTML page and returned to the user for viewing.
Summary
Although fairly simple, this chapter showed how dynamic web pages can be constructed using Visual Studio. There are many ways to build more visually interesting web pages than what's presented here. As stated at the beginning of the chapter, web programming is worthy of a complete book. (You should consider the Wrox book Beginning ASP.NET 4: in C# and VB by Imar Spaanjaars (Wrox, 2010). This well-received book has more than 800 pages of how to write programs for the web.) The goal here, however, is simply to enable you to start investigating this popular element of C# programming.
Exercises
You can find the answers to the following exercises in Appendix A.
1. What is a web page?
2. What is the difference between static and dynamic web pages?
3. What is meant by the term code-behind file?
4. Look at the code in Listing 18-3 to find a reason why it is SDC.
5. Given that question 4 suggests that the program can crash, how would you fix this?
What You Have Learned In This Chapter
Topic |
Key Points |
Web page |
An HTML document capable of being rendered in a web browser. |
Web Client |
The object that controls the web browser. |
Web Server |
The hardware that serves web pages to the client. It may or may not be responsible for page processing. |
Static versus Dynamic Web pages |
Static Web web pages have HTML content that does not change.Dynamic Web pages can respond to user (or other) input and alter the page rendering accordingly. |
Code-behind file |
The file that contains C# code that ASP.NET can process, thus affording the ability to alter the web page returned to the Client. |