Code-Behind Programming
While it's perfectly legal to put HTML and code in the same ASPX file, in the real world you should segregate the two by placing them in separate files. Proper separation of code and data is achieved in ASP.NET by using a technique called code-behind programming. A Web form that uses code-behind is divided into two parts: an ASPX file containing HTML and a source code file containing code. Here are two reasons why all commercial Web forms should employ code-behind:
RobustnessIf a programming error prevents the code in an ASPX file from compiling, the error won't come to light until the first time the page is accessed. Careful testing will take care of this, but how often do unit tests achieve 100 percent code coverage?
MaintainabilityASP files containing thousands of lines of spaghetti-like mixtures of HTML and script are not uncommon. Clean separation of code and data makes applications easier to write and to maintain.
Code-behind is exceptionally easy to use. Here's a recipe for using code-behind in Web forms coded in C#:
Create a CS file containing event handlers, help methods, and other codeeverything that would normally appear between <script> and </script> tags in an ASPX file. Make each of these source code elements members of a class derived from System.Web.UI.Page.
In your Page-derived class, declare protected fields whose names mirror the IDs of the controls declared in the ASPX file. For example, if the Web form includes a pair of TextBox controls whose IDs are UserName and Password, include the following statements in your class declaration:
protected TextBox UserName; protected TextBox Password;
Without these fields, the CS file won't compile because references to UserName and Password are unresolvable. At run time, ASP.NET maps these fields to the controls of the same name so that reading UserName.Text, for example, reads the text typed into the TextBox control named UserName.
Compile the CS file into a DLL and place the DLL in a subdirectory named bin in the application root.
Place the HTML portion of the Web formeverything between the <html> and </html> tagsin an ASPX file. Include in the ASPX file an @ Page directive containing an Inherits attribute that identifies the Page-derived class in the DLL.
That's it; that's all there is to it. You get all the benefits of embedding code in an ASPX file but none of the drawbacks. The application in the next section demonstrates code-behind at work.
The Lander Application
In 1969, Neil Armstrong landed the Apollo 11 Lunar Excursion Module (LEM) on the moon with just 12 seconds of fuel to spare. You can duplicate Armstrong's feat with a Web-based lunar lander simulation patterned after the lunar lander game popularized on mainframe computers in the 1970s. This version of the game is built from an ASP.NET Web form, and it uses code-behind to separate code and HTML. It's called Lander, and it's shown in Internet Explorer in Figure 6. Its source code appears in Listings 7 and 8.
To run the program, copy Lander.aspx (see Listing 7) to your PC's \Inetpub\wwwroot directory. If \Inetpub\wwwroot lacks a subdirectory named bin, create one. Then compile Lander.cs (see Listing 8) into a DLL and place the DLL in the bin subdirectory. Here's the command to compile the DLL:
csc /t:library Lander.cs
Next, start your browser and type
http://localhost/lander.aspx
into the address bar. Begin your descent by entering a throttle value (any percentage from 0 to 100, where 0 means no thrust and 100 means full thrust) and a burn time, in seconds. Click the Calculate button to input the values and update the altitude, velocity, acceleration, fuel, and elapsed time readouts. Repeat until you reach an altitude of 0, meaning that you've arrived at the moon's surface. A successful landing is one that occurs with a downward velocity of 4 meters per second or less. Anything greater, and you dig your very own crater in the moon.
Figure 6 The Lander application.
Lander.aspx is a Web form built from a combination of ordinary HTML and ASP.NET server controls. Clicking the Calculate button submits the form to the server and activates the DLL's OnCalculate method, which extracts the throttle and burn-time values from the input fields and updates the onscreen flight parameters using equations that model the actual flight physics of the Apollo 11 LEM. Like many Web pages, Lander.aspx uses an HTML table with invisible borders to visually align the page's controls.
Lander.aspx differs from the ASPX files presented thus far, in that it contains no source code. Lander.cs contains the form's C# source code. Inside is a Page-derived class named LanderPage containing the OnCalculate method that handles Click events fired by the Calculate button. Protected fields named Altitude, Velocity, Acceleration, Fuel, ElapsedTime, Output, Throttle, and Seconds serve as proxies for the controls of the same names in Lander.aspx. LanderPage and OnCalculate are declared public, which is essential if ASP.NET is to use them to serve the Web form defined in Lander.aspx.
Listing 7: The Lander Source Code: Lander.aspx
<%@ Page Inherits="LanderPage" %> <html> <body> <h1>Lunar Lander</h1> <form runat="server"> <hr> <table cellpadding="8"> <tr> <td>Altitude (m):</td> <td><asp:Label ID="Altitude" Text="15200.0" RunAt="Server" /></td> </tr> <tr> <td>Velocity (m/sec):</td> <td><asp:Label ID="Velocity" Text="0.0" RunAt="Server" /></td> </tr> <tr> <td>Acceleration (m/sec2):</td> <td><asp:Label ID="Acceleration" Text="-1.6" RunAt="Server" /></td> </tr> <tr> <td>Fuel (kg):</td> <td><asp:Label ID="Fuel" Text="8165.0" RunAt="Server" /></td> </tr> <tr> <td>Elapsed Time (sec):</td> <td><asp:Label ID="ElapsedTime" Text="0.0" RunAt="Server" /></td> </tr> <tr> <td>Throttle (%):</td> <td><asp:TextBox ID="Throttle" RunAt="Server" /></td> </tr> <tr> <td>Burn Time (sec):</td> <td><asp:TextBox ID="Seconds" RunAt="Server" /></td> </tr> </table> <br> <asp:Button Text="Calculate" OnClick="OnCalculate" RunAt="Server" /> <br><br> <hr> <h3><asp:Label ID="Output" RunAt="Server" /></h3> </form> </body> </html>
Listing 8: The Lander Source Code: Lander.cs
using System; using System.Web.UI; using System.Web.UI.WebControls; public class LanderPage : Page { const double gravity = 1.625; // Lunar gravity const double landermass = 17198.0; // Lander mass protected Label Altitude; protected Label Velocity; protected Label Acceleration; protected Label Fuel; protected Label ElapsedTime; protected Label Output; protected TextBox Throttle; protected TextBox Seconds; public void OnCalculate (Object sender, EventArgs e) { double alt1 = Convert.ToDouble (Altitude.Text); if (alt1 > 0.0) { // Check for blank input fields if (Throttle.Text.Length == 0) { Output.Text = "Error: Required field missing"; return; } if (Seconds.Text.Length == 0) { Output.Text = "Error: Required field missing"; return; } // Extract and validate user input double throttle; double sec; try { throttle = Convert.ToDouble (Throttle.Text); sec = Convert.ToDouble (Seconds.Text); } catch (FormatException) { Output.Text = "Error: Invalid input"; return; } if (throttle < 0.0 || throttle > 100.0) { Output.Text = "Error: Invalid throttle value"; return; } if (sec <= 0.0) { Output.Text = "Error: Invalid burn time"; return; } // Extract flight parameters from the Label controls double vel1 = Convert.ToDouble (Velocity.Text); double fuel1 = Convert.ToDouble (Fuel.Text); double time1 = Convert.ToDouble (ElapsedTime.Text); // Compute thrust and remaining fuel double thrust = throttle * 1200.0; double fuel = (thrust * sec) / 2600.0; double fuel2 = fuel1 - fuel; // Make sure there's enough fuel if (fuel2 < 0.0) { Output.Text = "Error: Insufficient fuel"; return; } // Compute new flight parameters Output.Text = ""; double avgmass = landermass + ((fuel1 + fuel2) / 2.0); double force = thrust - (avgmass * gravity); double acc = force / avgmass; double vel2 = vel1 + (acc * sec); double avgvel = (vel1 + vel2) / 2.0; double alt2 = alt1 + (avgvel * sec); double time2 = time1 + sec; // If altitude <= 0, then we've landed if (alt2 <= 0.0) { double mul = alt1 / (alt1 - alt2); vel2 = vel1 - ((vel1 - vel2) * mul); alt2 = 0.0; fuel2 = fuel1 - ((fuel1 - fuel2) * mul); time2 = time1 - ((time1 - time2) * mul); if (vel2 >= -4.0) Output.Text = "The Eagle has landed"; else Output.Text = "Kaboom!"; } // Update the Labels to show latest flight parameters Altitude.Text = alt2.ToString ("f1"); Velocity.Text = vel2.ToString ("f1"); Acceleration.Text = acc.ToString ("f1"); Fuel.Text = fuel2.ToString ("f1"); ElapsedTime.Text = time2.ToString ("f1"); } } }
How Code-Behind Works
A logical question to ask at this point is, "How does code-behind work?" The answer is deceptively simple. When you put Web forms code in an ASPX file and a request arrives for that page, ASP.NET derives a class from System.Web.UI.Page to process the request. The derived class contains the code that ASP.NET extracts from the ASPX file. When you use code-behind, ASP.NET derives a class from your classthe one identified with the Inherits attributeand uses it to process the request. In effect, code-behind lets you specify the base class that ASP.NET derives from. And because you write the base class, you control everything that goes in it.
Figure 7 shows (in ILDASM) the class that ASP.NET derived from LanderPage the first time Lander.aspx was requested. You can clearly see the name of the ASP.NET-generated classLander_aspxas well as the name of its base class: LanderPage.
Figure 7 DLL generated from a page that uses code-behind.
Using Code-Behind Without Precompiling: The Src Attribute
If you like the idea of separating code and data into different files but for some reason you prefer not to compile the source code files yourself, you can use code-behind and still allow ASP.NET to compile the code for you. The secret? Place the CS file in the same directory as the ASPX file and add a Src attribute to the ASPX file's @ Page directive. Here's how Lander.aspx's Page directive would look if it were modified to let ASP.NET compile Lander.cs:
<%@ Page Inherits="LanderPage" Src="Lander.cs" %>
Why anyone would want to exercise code-behind this way is a question looking for an answer. But it works, and the very fact that the Src attribute exists means someone will probably find a legitimate use for it.
Using NonASP.NET Languages in ASP.NET Web Forms
Code embedded in ASPX files has to be written in one of three languages: C#, Visual Basic .NET, or JScript. Why? Because even though compilers are available for numerous other languages, ASP.NET uses parsers to strip code from ASPX files and generate real source code files that it can pass to language compilers. The parsers are language-aware, and ASP.NET includes parsers only for the aforementioned three languages. To write a Web form in C++, you have to either write a C++ parser for ASP.NET or figure out how to bypass the parsers altogether. Code-behind is a convenient mechanism for doing the latter.
Code-behind makes it possible to code Web forms in C++, COBOL, and any other language that's supported by a .NET compiler. Listing 9 contains the C++ version of Lander.cs. Lander.cpp is an example of managed C++. That's Microsoft's term for C++ code that targets the .NET Framework. When you see language extensions such as __gc, which declares a managed type, being used, you know you're looking at managed C++.
The following command compiles Lander.cpp into a managed DLL and places it in the current directory's bin subdirectory:
cl /clr lander.cpp /link /dll /out:bin\Lander.dll
You can replace the DLL created from the CS file with the DLL created from the CPP file, and Lander.aspx is none the wiser; it still works the same as it did before. All it sees is a managed DLL containing the LanderPage type identified by the Inherits attribute in the ASPX file. It neither knows nor cares how the DLL was created or what language it was written in.
Listing 9: Lander.cpp: Managed C++ Version of Lander.cs
#using <system.dll> #using <mscorlib.dll> #using <system.web.dll> using namespace System; using namespace System::Web::UI; using namespace System::Web::UI::WebControls; public __gc class LanderPage : public Page { protected: static const double gravity = 1.625; // Lunar gravity static const double landermass = 17198.0; // Lander mass Label* Altitude; Label* Velocity; Label* Acceleration; Label* Fuel; Label* ElapsedTime; Label* Output; TextBox* Throttle; TextBox* Seconds; public: void OnCalculate (Object* sender, EventArgs* e) { double alt1 = Convert::ToDouble (Altitude->Text); if (alt1 > 0.0) { // Check for blank input fields if (Throttle->Text->Length == 0) { Output->Text = "Error: Required field missing"; return; } if (Seconds->Text->Length == 0) { Output->Text = "Error: Required field missing"; return; } // Extract and validate user input double throttle; double sec; try { throttle = Convert::ToDouble (Throttle->Text); sec = Convert::ToDouble (Seconds->Text); } catch (FormatException*) { Output->Text = "Error: Invalid input"; return; } if (throttle < 0.0 || throttle > 100.0) { Output->Text = "Error: Invalid throttle value"; return; } if (sec <= 0.0) { Output->Text = "Error: Invalid burn time"; return; } // Extract flight parameters from the Label controls double vel1 = Convert::ToDouble (Velocity->Text); double fuel1 = Convert::ToDouble (Fuel->Text); double time1 = Convert::ToDouble (ElapsedTime->Text); // Compute thrust and remaining fuel double thrust = throttle * 1200.0; double fuel = (thrust * sec) / 2600.0; double fuel2 = fuel1 - fuel; // Make sure there's enough fuel if (fuel2 < 0.0) { Output->Text = "Error: Insufficient fuel"; return; } // Compute new flight parameters Output->Text = ""; double avgmass = landermass + ((fuel1 + fuel2) / 2.0); double force = thrust - (avgmass * gravity); double acc = force / avgmass; double vel2 = vel1 + (acc * sec); double avgvel = (vel1 + vel2) / 2.0; double alt2 = alt1 + (avgvel * sec); double time2 = time1 + sec; // If altitude <= 0, then we've landed if (alt2 <= 0.0) { double mul = alt1 / (alt1 - alt2); vel2 = vel1 - ((vel1 - vel2) * mul); alt2 = 0.0; fuel2 = fuel1 - ((fuel1 - fuel2) * mul); time2 = time1 - ((time1 - time2) * mul); if (vel2 >= -4.0) Output->Text = "The Eagle has landed"; else Output->Text = "Kaboom!"; } // Update the Labels to show latest flight parameters Altitude->Text = (new Double (alt2))->ToString ("f1"); Velocity->Text = (new Double (vel2))->ToString ("f1"); Acceleration->Text = (new Double (acc))->ToString ("f1"); Fuel->Text = (new Double (fuel2))->ToString ("f1"); ElapsedTime->Text = (new Double (time2))->ToString ("f1"); } } };