Master C# Logo banner
Welcome to MasterCSharp.com - Master C#, the easy way... - by Saurabh Nandu

 


Creating your first Code Behind Page

Add Comment
 

 
Introduction
New to ASP.NET? Confused about what's code behind? Don't have Visual Studio.NET?
We read everywhere about ASP.NET's capabilities to separate the design and logic, is it possible without Visual Studio.NET?
Yes, it is and I will show you how easy it is. Read on for answers to your questions.

What would be the benefit's of separating the design from the code? 
In many production environments there are separate teams that work on each part of the Web Application. The Design team generally uses WYSWYG tools like Microsoft FrontPage or Macromedia DreamWeaver to design their pages while the programming team looks after the coding these pages according to the database etc... 
In previous technologies like ASP/JSP the code is mingled throughout the page along with the design, hence incase the design team modifies the design, there is a big possibility that they will overwrite some of the programming code too! This makes life hell for both the design and programming teams and many times leads to locked horns between the two!

In ASP.NET you can have two separate files, one for the design and another for the code. This is the most elegant solution, since the design team can work on the design page (with peace) and the programming team on their code without having to worry about  clashes between the two.
But, the problem arises that currently the whole code cannot be separated,  some code like the DataGrid Templates etc still need to be mingled with the design file, but still the extent of design/code separation possible is noteworthy! 
Another problem is that ASP.NET introduces new powerful and smart Web Controls, since the current editors don't support them currently, you will have to add those manually :(.

In this example I will try to illustrate the technique I use do design my HTML pages in MS FrontPage and then finally I change these page to a ASP.NET Code Behind files. I hope this can help you in your production environment!

CodeBehind Attribute vs. Code Behind Concept
There is a lot of confusion between these two terms, so I decided to clear it out for you!
ASP.NET supports the Code Behind Concept. According to this concept you can put your design code into a *.aspx file and place the programming code into a *.dll .NET PE file. This allows separation of design and code. Also within the 'Page' directive on the ASP.NET page you use the Inherits attribute to refer to the Class your page inherits.
Example
<%@ Page Language="C#" Inherits="Namespaces.ClassName" %>

The CodeBehind attribute, is specific to Visual Studio.NET and has no use for other users!
Visual Studio.Net use a directive like:

<%@ Page language="c#" Codebehind="myFile.aspx.cs" AutoEventWireup="false" Inherits="Project1.myFile" %>

This attribute is used by Visual Studio.NET to keep track of its files, and is of no use to non-Visual Studio.NET users.
I hope this has cleared out all your doubts regarding 'Code Behind'.

Example: ASP.NET Form Mailer

1) Create the HTML Page Design
This is the first step to create your Code Behind ASP.NET Web Page, since I am not a HTML Pro who would type all his design code in notepad, I use  MS FrontPage to create my design, although you can use any editor you like (even notepad if you are a Pro!!). I have created a very simple form, you can add all the bells and whistles that you want to add...

On the page create a normal table and a form like below

Figure 1: First Form in MS FrontPage

I have saved this page as first.htm. Check out the custom code generated by FrontPage below.

<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>Welcome to My First Code Behind Form</title>
</head>
<body>
<h3>Welcome to My First Code Behind Form - Saurabh Nandu</h3>
<form>
<table border="1" width="100%">
  <tr>
    <td width="100%" colspan="2">Please fill in the form</td>
  </tr>
  <tr>
    <td width="35%">Name</td>
    <td width="65%"><input type="text" name="Name" size="20"></td>
  </tr>
  <tr>
    <td width="35%">E-Mail</td>
    <td width="65%"><input type="text" name="Email" size="20"></td>
  </tr>
  <tr>
    <td width="35%">Message</td>
    <td width="65%"><textarea rows="7" name="Message" cols="26"></textarea></td>
  </tr>
  <tr>
    <td width="100%" colspan="2"><input type="submit" value="Submit" name="B1"></td>
  </tr>
</table>
</form>
<p><a href="http://www.MasterCSharp.com">www.MasterCSharp.com</a> - Master C#,
the easy way...</p>
</body>
</html>
 

2) Creating the Virtual Directory (Programming Department work starts here!)
As the next step, I take this file and copy it to the Virtual Directory that will host the ASP.NET application, I use a Virtual Directory named FirstForm, if you have created a Virtual Directory then first create a normal folder in Windows Explorer under the c:\InetPub\WWWRoot directory called as C:\InetPub\WWWRoot\FirstForm and then got to Start - > Control Panel -> Administrative Tools -> Internet Services Manager. Within the Internet Services Manager, select Default Web Site. Under this tab, select FirstFolder and click Action -> Properties to view the properties of this folder. In the properties tab, click on the Create button (see figure below) to create a new Virtual Directory. Remember you need to have proper rights to do this!!


Figure 2: Properties Panel - Internet Services manager

3) Creating in-line coded ASP.NET File
Once you have the created the virtual directory and copied the first.htm file into this directory, rename this file to first.aspx (I hope you know how to rename files, don't U??). Now open this file in Notepad or any other plain text editor (time to become a Pro!!). I first compile the files with in-line coding and then convert it into Code Behind files, even though this is one extra step, but its always easier to debug, once the in-line version of the page is working, you can easily shift it into a code behind file.
Now follow these steps precisely..

A) Add the Page directive
Go to the first line in notepad and add the following directive to state that out ASP.NET page will use C# as the coding language.
<%@ Page Language="C#" %>

B) Convert all the Form elements to HtmlControls
HtmlControls as special ASP.NET controls that can be accessed by server-side scripting. To convert normal Form components to HtmlControls, go to each Form component (including the Form declaration) that has been defined within the web page and add a runat="server"  attribute, as well as to make the tags 'well formed' close the tags with a '/' symbol. We also have to add the 'ID' attribute, which is used by ASP.NET to identify the controls, we use the same values for the 'ID' attribute that we set on the 'name' attribute in FrontPage. Also note that I add a OnServerClick event handler for the button and wire it up to the Post_Form server-side method (we will define this below). So make the following changes.

HTML HTML Control
<form> <form runat="server" >
<input type="text" name="Name" size="20" > <input type="text" id="Name" name="Name" size="20" runat="server" />
<input type="text" name="Email" size="20" > <input type="text" id="Email" name="Email" size="20" runat="server" />
<textarea rows="7" name="Message" cols="26"></textarea> <textarea rows="7" id="Message" name="Message" cols="26" runat="server"></textarea>
<input type="submit" value="Submit" name="B1"> <input type="submit" id="B1" value="Submit" name="B1"  OnServerClick="Post_Form" runat="server" />
 

C) Adding the In-Line Code
Once the controls have been changed to HtmlControls that run at server, we next write the necessary server-side script, to mail the form contents. I am using a simple SMTP mailer script, which will e-mail the contents of the form to the specified address, remember you should have SMTP service running on your web server for this script to work!
I am presenting the full modified code of the first.aspx with the in-line script added. You can call this file in your browser and test it. 
Note: I am using the SmtpMail class from the System.Web.Mail namespace to e-mail the form contents. The static method Send takes the following parameters
1) Email address from which the mail has been sent.
2) Email address to which the mail should go.
3) Subject line.
4) Body of the message
.
You will also note, that HtmlContols have the property Value that returns its text, unlike the Text property of the Web Control that returns the controls text.

<%@ Page Language="C#" %>
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>Welcome to My First Code Behind Form</title>
<script runat="server">
  protected void Post_Form(object sender, EventArgs e)
  {
    //Check if the Name and Email fields are filled in
    if(Name.Value!=""&&Email.Value!="")
    {
      //Send the Mail
      System.Web.Mail.SmtpMail.Send(Email.Value,"saurabh@mastercsharp.com",
			"Mail From:"+Name.Value,Message.Value);
    }
  }
</script>
</head>
<body>
<h3>Welcome to My First Code Behind Form - Saurabh Nandu</h3>
<form runat="server">
<table border="1" width="100%">
  <tr>
    <td width="100%" colspan="2">Please fill in the form</td>
  </tr>
  <tr>
    <td width="35%">Name</td>
    <td width="65%">
    <input type="text" id="Name" name="Name" size="20" runat="server" />
    </td>
  </tr>
  <tr>
    <td width="35%">E-Mail</td>
    <td width="65%">
    <input type="text" id="Email" name="Email" size="20" runat="server" />
     </td>
  </tr>
  <tr>
    <td width="35%">Message</td>
    <td width="65%"><textarea rows="7" id="Message"
   name="Message" cols="26" runat="server">
    </textarea></td>
  </tr>
  <tr>
    <td width="100%" colspan="2">
<input type="submit" value="Submit" id="B1" name="B1" OnServerClick="Post_Form"
    runat="Server" />
</td>
  </tr>
</table>
</form>
<p><a href="http://www.MasterCSharp.com">www.MasterCSharp.com</a> - Master C#,
the easy way...</p>
</body>
</html>
 

4) Creating the first Code Behind file.
If the above page is working correctly, then we proceed further with separating the code from the design. Follow the below steps ....

A) Create a *.cs source code file
Within the Virtual Directory that hosts your application (FirstForm in our example) create a new First.cs file and open it up in notepad. 

B) Copy the Script into the Code file.
Next, cut the script i.e. everything from <script runat="server"> to </script> (including the script tags) from the ASP.NET page (first.aspx) to the source code file (first.cs). 

D) Update the Code File
The Source Code file is like a normal C# program file, hence we need to update the file with the necessary changes to change it into a valid C# program file.

C# Code file without changes (first.cs)

<script runat="server">
  protected void Post_Form(object sender, EventArgs e)
  {
    //Check if the Name and Email fields are filled in
    if(Name.Value!=""&&Email.Value!="")
    {
      //Send the Mail
      System.Web.Mail.SmtpMail.Send(Email.Value,"saurabh@mastercsharp.com",
			"Mail From:"+Name.Value,Message.Value);
    }
  }
</script>

The updated source code file with the necessary changes to make it into a proper C# class.
using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
public class First:Page
{
  //Declare all the Controls used
  protected HtmlInputControl Name, Email;
  protected HtmlTextArea Message;

  public void Post_Form(object sender, EventArgs e)
  {
    //Check if the Name and Email fields are filled in
    if(Name.Value!=""&&Email.Value!="")
    {
      //Send the Mail
      System.Web.Mail.SmtpMail.Send(Email.Value,"saurabh@mastercsharp.com",
			"Mail From:"+Name.Value,Message.Value);
    }
  }
}

As its clear from above, the first step is to import the necessary Namespaces, in our case System, System.Web.UI and System.Web.UI.HtmlControls.
The second step is to replace the <script runat="server"> tag with
public class First:Page {

i.e. a class declaration of the class First. Also remember that all ASP.NET web pages inherit the Page class from the System.Web.UI namespace. The closing </script> tag is replaced by a closing bracket }.
Lastly, we have to declare all the controls, that we are referencing in our code, this can be a bit tricky, but just browse the code for see which controls, you have referenced in your page. Its not necessary to declare all the controls used on the page, just declare the controls you are using in the code. In the above example we have a number of controls such as 'Input Textboxes', 'TextArea', 'Form' and a 'Input Button', but in the code since I am just referencing the 'Input Textboxes' and 'TextArea' I just declare those variables. Although you might think it to be best practice to declare all the variables used, incase you might need them in the future!
Ps: If you are thinking how did I get the Variable names? Well just look at the 'ID' tags in all the controls with the runat server attribute and declare the control with the same name as the ID. (Does this make sense??).

E) Update the Design file (first.aspx)
Most of the work is done! Just you have to let the ASP.NET runtime know where you have stored the code of the code behind file. Hence we have to update the Page directive to reflect the necessary changes.
Here is the updated ASP.NET File (first.aspx)

<%@ Page Language="C#" Inherits="First" Src="First.cs" %>
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>Welcome to My First Code Behind Form</title>
</head>
<body>
<h3>Welcome to My First Code Behind Form - Saurabh Nandu</h3>
<form runat="server">
<table border="1" width="100%">
  <tr>
    <td width="100%" colspan="2">Please fill in the form</td>
  </tr>
  <tr>
    <td width="35%">Name</td>
    <td width="65%">
    <input type="text" id="Name" name="Name" size="20" runat="server" />
  </td>
  </tr>
  <tr>
    <td width="35%">E-Mail</td>
    <td width="65%">
    <input type="text" id="Email" name="Email" size="20" runat="server" />
  </td>
  </tr>
  <tr>
    <td width="35%">Message</td>
    <td width="65%">
    <textarea rows="7" id="Message" name="Message" cols="26" runat="server">
    </textarea></td>
  </tr>
  <tr>
    <td width="100%" colspan="2"><input type="submit" value="Submit" id="B1" name="B1"
    OnServerClick="Post_Form" runat="Server" /></td>
  </tr>
</table>
</form>
<p><a href="http://www.MasterCSharp.com">www.MasterCSharp.com</a> - Master C#,
the easy way...</p>
</body>
</html>

The Inherits attributa tell the runtime which class the page inherits, and the Src attribute tells the runtime which file contains the source code for the page class.

That does it! You have separated your code and design into two separate files!! What an achievement !! Try calling the first.aspx page in your browser .... It should work just like magic!
Just a tip for the brave hearts, you can configure HTML editor like MS FrontPage  as the default editor for *.aspx files. In MS FrontPage go to Tools -> Options -> Configure Editors and add a reference to *.aspx. Since now your code is separate from the design, your design team can continue to work on the design of '*.aspx' files without having to worry of causing any damage to your work! Isn't that kool !!

5) Compiling the Source Code into a PE file
The above solution works very well in production environments, you can just make changes to the source code file and the subsequent requests will gracefully use the updated code. If you have a look at the internal process of ASP.NET, when the page with code behind is called for the first time, it gets compiled and then its loaded into memory and subsequent requests are served from the memory. When you update the source code, the runtime senses it and compiles the new code again and subsequent requests are served from the new copy.

When we are developing solutions for clients many times we are not comfortable to distribute the source code along with the application, since the client's team could at a future date use some of our functions and algorithms. There was little you could do with plain ASP to avoid this, but ASP.NET provides an elegant solution to this problem too! Instead of placing the source code, you can just distribute the compiled Dll's along with your application! Since the Dll's are compiled your code gets safeguarded!

Diving into how to achieve this,
a) Create the 'bin' directory
The ASP.NET runtime can automatically pickup/reference assemblies for web applications from the bin directory. So create the bin directory within our firstform directory. i.e. its full path should be 'C:\InetPub\WWWRoot\FirstForm\Bin'. The bin directory should be typically located within the Virtual Directory, incase you have other applications nested within a Virtual Directory, still the bin directory will reside within the Virtual Directory and not the nested directory.

b) Compile the Source Code.
Open the Command Prompt, and navigate to the directory holding our source code file first.cs (directory C:\InetPub\WWWRoot\FirstForm\). Then use the following command to compile the code.
csc /t:library /r:System.dll;System.Web.dll /out:bin/First.dll First.cs
This will create a First.dll library assembly in the bin directory.

c) Updating the ASP.NET Page
Since now we will be using compiled Dll and not the source code, move the first.cs source code file to some other temporary directory (you don't want to distribute the source code too, right!!).
Now update the ASP.NET page first.aspx and remove the Src="First.cs"  attribute from the first line and Save the page.
So the final updated design page becomes,

<%@ Page Language="C#" Inherits="First"  %>
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>Welcome to My First Code Behind Form</title>
</head>
<body>
<h3>Welcome to My First Code Behind Form - Saurabh Nandu</h3>
<form runat="server">
<table border="1" width="100%">
  <tr>
    <td width="100%" colspan="2">Please fill in the form</td>
  </tr>
  <tr>
    <td width="35%">Name</td>
    <td width="65%">
    <input type="text" id="Name" name="Name" size="20" runat="server" /></td>
  </tr>
  <tr>
    <td width="35%">E-Mail</td>
    <td width="65%">
    <input type="text" id="Email" name="Email" size="20" runat="server" /></td>
  </tr>
  <tr>
    <td width="35%">Message</td>
    <td width="65%">
    <textarea rows="7" id="Message" name="Message" cols="26" runat="server">
    </textarea>
    </td>
  </tr>
  <tr>
    <td width="100%" colspan="2"><input type="submit" value="Submit" id="B1" name="B1"
         OnServerClick="Post_Form" runat="Server" /></td>
  </tr>
</table>
</form>
<p><a href="http://www.MasterCSharp.com">www.MasterCSharp.com</a> - Master C#,
the easy way...</p>
</body>
</html>

Call the page again from your browser.... wolla! You have succeeded!!
On the side note, COM programmers should not worry, since this Dll does not require any more registration, nor is it locked down by the operating system.
Internally, the ASP.NET runtime creates a copy of the dll in its memory, all requests are served from this copy, hence your Dll is always free. To update the code, just XCopy the updated code and the runtime will sense the change and create another fresh copy of the code in memory and subsequent requests will be served from the new code!

Conclusion
I hope I have been descriptive enough to describe this trivial but easy and powerful process of separating code from design! Happy coding :)

Comments

Add Comment