Home > Articles > Programming > Windows Programming

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:

  • Robustness—If 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?

  • Maintainability—ASP 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#:

  1. Create a CS file containing event handlers, help methods, and other code—everything 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.

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

  3. Compile the CS file into a DLL and place the DLL in a subdirectory named bin in the application root.

  4. Place the HTML portion of the Web form—everything between the <html> and </html> tags—in 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 class—the one identified with the Inherits attribute—and 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 class—Lander_aspx—as 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 Non–ASP.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");
    }
  }
};

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