What Are ASP.Net WebForms

An introduction and guide to Microsoft's server-side scripting language for creating dynamic websites in ASP.Net WebForms!

6,143 words, estimated reading time 24 minutes.
Introduction to Programming with C#

This article is part of a series of articles. Please use the links below to navigate between the articles.

  1. Learn to Program in C# - Full Introduction to Programming Course
  2. Introdution to Programming - C# Programming Fundamentals
  3. Introduction to Object Oriented Programming for Beginners
  4. Introduction to C# Object-Oriented Programming Part 2
  5. Application Flow Control and Control Structures in C#
  6. Guide to C# Data Types, Variables and Object Casting
  7. C# Collection Types (Array,List,Dictionary,HashTable and More)
  8. C# Operators: Arithmetic, Comparison, Logical and more
  9. Using Entity Framework & ADO.Net Data in C# 7
  10. What is LINQ? The .NET Language Integrated Query
  11. Error and Exception Handling in C#
  12. Advanced C# Programming Topics
  13. All About Reflection in C# To Read Metadata and Find Assemblies
  14. What Are ASP.Net WebForms
  15. Introduction to ASP.Net MVC Web Applications and C#
  16. Windows Application Development Using .Net and Windows Forms
  17. Assemblies and the Global Assembly Cache in C#
  18. Working with Resources Files, Culture & Regions in .Net
  19. The Ultimate Guide to Regular Expressions: Everything You Need to Know
  20. Introduction to XML and XmlDocument with C#
  21. Complete Guide to File Handling in C# - Reading and Writing Files

Active Server Pages, or ASP, is a platform for building scalable websites using the .Net framework. ASP.Net is the successor to ASP 2.0 and makes use of the .Net platform to integrate data and controls on web forms and enables information to be sent via the Internet.

While ASP.Net Web Forms are still in use, it is highly advisable to create new projects using the MVC structure. Web forms are outdated and rely on old methodologies. MVC allows for a much more fluid and extendable solution. This tutorial is left as a reference only.

ASP.Net web form content is browser independent, meaning that pages will render the same under Internet Explorer, Firefox, Opera or Safari, and they are language-independent.

ASP.Net Execution Model

ASP.Net pages are stored as text files on the server, however, when the page is accessed they are compiled to MSIL so that the C# and .Net framework can be run in the CLR. To improve performance, ASP.Net uses output caching to prevent pages from being compiled and executed unnecessarily.

The .Net Platform and Code Distribution
The .Net Platform and Code Distribution

File Extension Types

ASP.Net has a few different source code file extensions:

  • ASP.Net Web Forms (.aspx)
  • ASP.Net Web Services (.asmx)
  • Classes and code-behind (.vb or .cs)
  • Global application classes (.asax)
  • web.config file
  • Project assembly (.dll)

Web forms contain the dynamic content and HTML elements of the page, and the code behind is the C# code that generates the data, accesses databases and so on. The project assembly contains the C# code compiled into executable form for faster performance. The web.config contains settings for the application.

Common Controls

Because of the common type system of the .Net Framework, the server classes and controls that you use in a web form are the same controls and classes that you would use in a Windows Forms application. This allows for greater code reuse between Windows Forms developers and web forms developers. It also makes it easier to migrate existing Windows applications to web-based forms and web services.

Test Environment

Visual Studio and Visual Web Developer both come with a limited version of IIS (Internet Information Services) that can be used for local connections only. It will allow you to develop and test websites and servers on a local machine using the loopback interface, but it will not accept connections from external machines so you will need an IIS server to deploy onto.

Creating a Simple ASP.Net Page

When you create a new ASP.Net page, by default the page will contain bare-bones skeleton XHTML code as shown below.

C#
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-/W3C/DTD XHTML 1.0 Transitional/EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

The first line defines a few things that the framework needs to know about the page. It is not sent to the browser. It defines what language the page uses, where the code behind is located, the class that this page inherits from and whether to automatically assign event handlers. This line is automatically generated and 99% of the time you don't need to change it.

The next two lines are the standard HTML doctype and HTML header tags. You should already be familiar with these. Within the body tag, you will notice that there is a form with an attribute runat="server". This tag tells the ASP.Net compiler that the events within that element should be processed on the server rather than the client. Within this form, your normal page content will go in the div tag.

This simple ASP.Net page is rendered on the browser as:

C#
<!DOCTYPE html PUBLIC "-/W3C/DTD XHTML 1.0 Transitional/EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Untitled Page</title></head>
<body>
  <form name="form1" method="post" action="Default.aspx" id="form1">
    <div>
      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNzgzNDMwNTMzZGS29dOTDoX35MyeDN3AYOtFbdG9ww==" />
    </div>
  </form>
</body>
</html>

You will notice that there is a hidden input object within the client code and the "runat" tag has been removed from the form tag. The hidden input object is a required element and is produced on every ASP.Net page. The view state contains an encrypted name-value pair for the items on the form. This is used to maintain the status of the page when it is submitted to the server. The view state prevents the form values from being lost when going back.

Building a Page

You can put any valid HTML on the page, but it is often better to use standard ASP.Net controls as these have additional features managed by the platform.

You can "upgrade" a standard HTML form element to an ASP.Net control by right-clicking it and selecting Run as Server Control. This will add the required runat="server" tag to the control for you.

One of the first things you will probably create is the Page_Load method. The easiest way of doing this is to double-click the page in the designer. This will auto-wire up the event for onPageLoad. Within this method, you can set up the form properties, fill in default values and so on. One of the first things you may want to do is set the page title from the default "Untitled Page" to something more meaningful. This can be done by accessing the page object.

C#
Page.Title = "This is my Page!!!";

All of the ASP.Net controls, including the Page object, exist in the System.Web.UI.WebControls namespace. ASP components that are added to a page usually start with an <asp: tag, for example, an input box in ASP.Net:

C#
<asp:TextBox id="TextBox1" runat="server">Hello World</asp:TextBox>

This will be rendered on the browser as:

C#
<input name="TextBox1" type="text" value="Hello World" Id="TextBox1"/>

You can change any of the properties of a control from within the editor using the properties window, or you can change them at runtime in the code behind.

C#
TextBox1.Text = "Another Sample";

Adding Code to a Page

There are three ways of adding code to a page. We have already touched on Code Behind pages, but you can also insert code in the same file as the HTML elements (combined) or embed code within the HTML itself (inline).

The Code Behind method stores all the code in a separate file, usually, the page name with .cs appended to the extension. The intention for this method is that you keep the layout separate from the implementation, and style from a function.

Combined mode puts the C# (or Visual Basic) code at the top or bottom of the layout page and the inline method places blocks of code anywhere within the layout page. The inline method is most commonly used in the PHP language. .Net defaults to Code Behind pages.

We have seen that some elements are marked with a runat="server" attribute. This tells the platform that the events for this element are to be handled using server-side code in C# or VB.Net. You can double-click on elements in the designer and it will create default event methods just like Windows Forms coding.

C#
<asp:Label ID="lblEnterSomeText" runat="server" Text="Enter some text: "></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" Text="Submit" onclick="Button1_Click" />
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
C#
protected void Button1_Click(object sender, EventArgs e)
{
  lblResult.Text = TextBox1.Text;
}

In this example when the user clicks on the button the contents of the text box are shown in the label below.

Postbacks

When you submit a form to the server on the same page as the form was displayed on you are invoking a process known as Postback. There is a method called IsPostBack() which can be used to determine if the current page is a postback or a first access. It's probably easier to see than explain. Modify the code above to include a Page_Load event method:

C#
protected void Page_Load(object sender, EventArgs e)
{
  if (IsPostBack)
  {
    lblEnterSomeText.Visible = false;
    lblResult.Visible = true;  
    TextBox1.Visible = false;
    Button1.Visible = false;
  }
  else
  {
    lblEnterSomeText.Visible = true;
    lblResult.Visible = false;
    TextBox1.Visible = true;
    Button1.Visible = true;
  }
}

What this code will do is hide the input box and button when the form is posted back - i.e. just showing the result. This isn't the best method for hiding elements, but it gives an impression of how the IsPostBack works. You could use it to show/hide options as required or to process submitted data.

Using ASP.Net Master Pages and Content Pages

Master pages allow the same content to be displayed on multiple pages, typically they are used for headers, footers and sidebars.

Master pages are created from the new item screen and should be given a meaningful name. One master page will contain the header, footer, any sidebars and a placeholder for the content. When creating a new asp.net web form you are given the option to select a master page. This will link to the content page with the master page.

You should notice that the master page contains all the HTML header tags as well as the body tag. In between the body tag is a ContentPlaceHolder. When a request for the content page is made it is merged with the master page and the ContentPlaceHolder object is replaced with the content within the content page. Master pages cannot be invoked through a browser as themselves, only through a content page.

My basic master page looks like this:

C#
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-/W3C/DTD XHTML 1.0 Transitional/EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div class="header"><h1>This is my Website Header</h1></div>
    <div>
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        </asp:contentplaceholder>
    </div>
    <div class="footer"><h1>This is my Website Footer</h1></div>
    </form>
</body>
</html>

Notice that the default page title is "Untitled Page". Should be changed to your site or you can override the title from the content page (see below).

The content page in my example sets the title attribute and writes out a paragraph.

C#
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" Title="My Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
 This is my content


</asp:Content>

The result when requesting default2.aspx from the server is:

C#
<div class="header"><h1>This is my Website Header</h1></div>
<div>
  This is my content


</div>
<div class="footer"><h1>This is my Website Footer</h1></div>

In the content page, I have set the title to "My Page" and this is intercepted by ASP.Net and the default Untitled Page is overwritten.

Validating Input using ASP.Net

Validation of data is vital when capturing information from a user. Validation can be as simple as checking that a field has been filled in or more complex such as range checking and format checking.

The .Net platform provides a set of components for form validation that can be found in the Validation section of the toolbox.

We are going to start with a basic form that asks for a name and a telephone number. It's a simple form, but we are not going to any design awards here!

C#
<asp:Label ID="lblName" runat="server" Style="position: relative" Text="Name:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>


<asp:Label ID="lblTelephone" runat="server" Style="position: relative" Text="Telephone:"></asp:Label>
<asp:TextBox ID="txtTelephone" runat="server"></asp:TextBox>




<asp:Button ID="btnSubmit" runat="server" Style="position: relative" Text="Submit" />

When you build and run the application you will notice that you can submit the form without any information entered and you can also submit the form with numbers in the name field and vice versa. This will result in useless data.

Required Field Validator

The simplest form of validation is to make a field a required field. This will ensure that the specified field contains some data, although it may not be valid data. The RequiredFieldValidator can be dragged onto a form, one for each control to be validated.

C#
<asp:Label ID="lblName" runat="server" Style="position: relative" Text="Name:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter a name." ControlToValidate="txtName"></asp:RequiredFieldValidator>


<asp:Label ID="lblTelephone" runat="server" Style="position: relative" Text="Telephone:"></asp:Label>
<asp:TextBox ID="txtTelephone" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter a number." ControlToValidate="txtTelephone" ></asp:RequiredFieldValidator>




<asp:Button ID="btnSubmit" runat="server" Style="position: relative" Text="Submit" />

Now when you run the application you will not be able to submit the form unless both text boxes contain data. While this may serve most purposes, we can go one further and require that the name field can only contain letters, spaces and hyphens and that the telephone number field only contains numbers. We can do this using a RegularExpressionValidator.

Regular Expression Validator

This is a more advanced validator and it allows a form to be submitted if the contents of the control match a regular expression. This allows for a wide range of validation rules to be used including checking the correct format of credit card numbers, social security numbers, telephone numbers and even a product or style code.

A Regular Expression Validator will be in addition to any Required Field Validator assigned to the control. You must set the ControlToValidate and ErrorMessage property as before, however, you must also specify a ValidationExpression string that contains a valid regex.

C#
<asp:Label ID="lblName" runat="server" Style="position: relative" Text="Name:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="txtName">Required</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ControlToValidate="txtName" ID="RegularExpressionValidator1" runat="server" ErrorMessage="Please only enter letters, spaces and hyphens" ValidationExpression="^[a-zA-Z -]*$"></asp:RegularExpressionValidator>


<asp:Label ID="lblTelephone" runat="server" Style="position: relative" Text="Telephone:"></asp:Label>
<asp:TextBox ID="txtTelephone" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="txtTelephone">Required</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ControlToValidate="txtTelephone" ID="RegularExpressionValidator2" runat="server" ErrorMessage="Please only enter numbers (0-9)" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>




<asp:Button ID="btnSubmit" runat="server" Style="position: relative" Text="Submit" />

Limit Number of Characters

Sometimes it may be required to validate the length of a string or number, for example, you may only want a four-digit number to be entered. You can do this from within the regular expression.

C#
<asp:RegularExpressionValidator ControlToValidate="txtTelephone" ID="RegularExpressionValidator2" runat="server" ErrorMessage="Please only enter numbers (0-9)" ValidationExpression="^[0-9]{4}$"></asp:RegularExpressionValidator>

In this example, the addition of {4} will limit the number of characters entered to four. If less than four or more than four are entered then the error message will be displayed.

Using Multiple Validators

You can use multiple validation objects on a control, just add them to the form, set them up and assign the ControlToValidate property. One thing you will notice is the position of the controls relative to the position on the form.

Validating Input using ASP.Net
Validating Input using ASP.Net

The controls appear at runtime in the same position that they were in design time. This may be an undesired position as it is visually more impressive if a validation text is located next to the box in question. You can force all validators to appear in the same location by setting the display property from Static to Dynamic.

Validating Input using ASP.Net
Validating Input using ASP.Net

Page Validation

The Page object accessible from the C# code behind has a property called IsValid which can be used to determine if there are validation errors on the page. IsValid contains the combined result of all the validators on the page.

C#
if (Page.IsValid)
{
  Message.Text = "Page is Valid";
}

Validation Summary

A validation summary object can be used to provide a list of fields that are in error. As well as setting the ErrorMessage of the validator to the customer-friendly message (i.e. "Name cannot be left blank.") we also need to set the Text property to identify the control in error, most commonly an asterisk is used.

C#
<asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="The following errors were found:" />
Name:

<asp:TextBox ID="TextBox2" runat="server" Style="left: 0px; position: relative"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
ErrorMessage="Name cannot be blank." Style="position: relative">*</asp:RequiredFieldValidator>

The ValidationSummary object will only be shown when a control is in an error state.

Validating Input using ASP.Net
Validating Input using ASP.Net

Managing Session State in ASP.Net

HTTP is a stateless protocol which means that each request is processed as it comes; after the request has been processed all of the data is discarded. No state is maintained across requests even from the same client.

ASP.Net provides a set of functionality to maintain a state which can be managed by the client or the server.

Imagine a web form (name.aspx) that asks for a name and shows that name on another page (hello.aspx). In a stateless environment (figure 1) hello.aspx does not know about the information from name.aspx because the data has been discarded. Figure 2 illustrates that in a managed state environment hello.aspx is aware of the data entered.

Managing Session State in ASP.Net
Managing Session State in ASP.Net

Types of State Management

Server Side Client Side
Application State
Information is available to all users of a web application.
Cookies
Text files store information to maintain state. The cookie is sent to the server with the information on each page request.
Session State
Information is only available to a user of a specific session
ViewState Property
Retains values between multiple request for the same page.
Database
SQL Server can store and maintain state on a website.
Query Strings
Information is encrypted and appended to the end of a URL.

Session ID and Cookies

A session in ASP.Net is identified with a SessionID string which is by default stored as a cookie on the client's computer; however, they are less reliable than server-side management options since cookies can be deleted or modified by the user, or cookies can be disabled. If cookies have been disabled by a client then the session state cannot be maintained using this method and you should use query strings instead.

Query Strings (cookieless)

If cookies cannot be used to store the SessionID then query strings must be used instead. This involved storing the session id within the URL of the page being requested. This is done automatically by the ASP.Net managed code, but it does mean that you cannot generate URLs yourself - they must all come from ASP.Net components.

An example of a query string is http://localhost/QueryStringDemo/(g4gns8dbldow83b2x)/Default.aspx

There are several issues with using query strings including search engines, duplicate URLs and the possibility of session id tampering. Because there is a limit of 255 characters for the length of a URL you are also limited to the amount of information that can be stored within a query string id.

To enable cookieless state management you need to set the sessionState section of the web config:

C#
<sessionState cookieless="true" />

Application State

Application state is a global storage mechanism accessible from all pages by all users in the web application. Application state can be set and accessed using the Application object.

C#
int numberVisitors = Application["NumberOfVisitors"];
Application["SiteName"] = "My Website Title";

Session State

Session state is a storage mechanism accessible by the user of a single session. Data cannot be transferred between sessions, nor can one session access the data of another session. Session State should be used to store information about a user or connection and can be accessed or set using the Session object.

C#
Session["UserName"] = LoginForm.Username.Text;
Response.Write("Hello " + Session["UserName"]);

Session State requires that a session cookie be loaded onto the client's computer, or a cookie-less implementation involving query strings be used.

Database

By default, the session state information is stored in the process. The advantage is that it is quickly accessible; however, this does not lead to a scalable application. To create a scalable session state management process, state data can be stored within a SQL Server database known as a state server.

To enable state servers you need to change the sessionState section of the web.config file.

C#
<sessionState mode="SQLServer" sqlConnectionString="data source=sqlServerName; Integrated security =true" />

On the SQL server, you need to prepare it to act as a session server by invoking this command on the command line:

C#
C:\OSQL -S SqlServerName -E InstallSqlState.sql

Where SqlServerName is the name of the server. This command will execute the commands within the InstallSqlState file to create the databases and tables required.

ViewState

ViewState is used to store the values submitted on a form and only works between requests on the same page. ViewState is most useful when a form is submitted and presented to the user a second time, maybe to correct an error, and the controls retain the information entered the first time. Without ViewState, these values would have been lost.

ASP.Net Website Navigation Using a SiteMap

A website with only one page isn't much use, so we will guide you through adding more pages to your project and linking them together with Hyperlinks, Navigation Menus and Site Map Paths.

I have created a basic website with a few sample pages (File » New » File » Web Form) to mimic a business site. These pages all inherit from a Master Page into which I will insert the navigation elements. I have created a series of pages that will mimic a business website.

You will also need to create an XML Sitemap for the project as this will be used for some of the navigation items and page titles.

ASP.Net Website Navigation Using a SiteMap
ASP.Net Website Navigation Using a SiteMap

Sitemaps

Sitemaps are an XML format document that is used by the navigation controls to allow navigation between pages. This is a Microsoft proprietary format and should not be confused with a Google XML Sitemap. The role of the sitemap is to inform ASP.Net how the pages of the site interact and relate to each other. You can add a sitemap from the Add New Item dialogue. This is how the sitemap looks for my sample site:

C#
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
    <siteMapNode url="Default.aspx" title="Home"  description="This is our homepage">
      <siteMapNode url="about.aspx" title="About Us"  description="This page is all about our company" />
      <siteMapNode url="products.aspx" title="Products"  description="This is our main product page" >
        <siteMapNode url="product1.aspx" title="Sample Product 1"  description="This is a sample product" />
        <siteMapNode url="product2.aspx" title="Sample Product 2"  description="This is a sample product" />
      </siteMapNode>
      <siteMapNode url="services.aspx" title="Our Services"  description="These are the services we provide" />
      <siteMapNode url="contact.aspx" title="Contact Us"  description="How to contact us">
        <siteMapNode url="map.aspx" title="How to Find Us"  description="A Map of how to find us" />
      </siteMapNode>
    </siteMapNode>
</siteMap>

From this, we can see that two sample products are child pages of the main product page and we have a map as a child of the contact us page. We can use a feature of the Sitemap object to use the title and description specified here from within the content and master page.

In the MasterPage, I am going to use the title property to specify the page title, and in the content page, I am going to write a header tag with the title. You can also use the same technique for the meta description if you wish.

C#
<title><%= SiteMap.CurrentNode.Title %></title>

Title Tag from XML Sitemap in Master Page

C#
<h1><%= SiteMap.CurrentNode.Title %></h1>
<em><%= SiteMap.CurrentNode.Description%></em>

Heading from XML Sitemap in Content Page

Hyperlinks

You are probably familiar with the standard   style of the hyperlink, but ASP.Net provides a hyperlink object which links to existing pages. This object is found within the standard items of the toolbox and is configurable from the properties window.

C#
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="products.aspx" Text="Products">Products</asp:HyperLink>

This will be rendered on the browser as

C#
<a id="ctl00_ContentPlaceHolder1_HyperLink1" href="products.aspx">Products</a>

Navigation Tree

Navigation trees provide a collapsible, hierarchical list of the pages on the side. It shows each page in an indented list like the folder view on Windows Explorer. Navigation levels can be set to expand or collapse if they contain child categories. I have placed my TreeView object on the master page and contained it with a div that aligns right.

C#
<div style="float:right">
  <asp:TreeView ID="TreeView1" runat="server" DataSourceID="SiteMapDataSource1" >
  </asp:TreeView>
  <asp:SiteMapDataSource ID="SiteMapDataSource1" Runat="server"></asp:SiteMapDataSource>
</div>

The SiteMapDataSource object creates a link between the TreeView and the web.sitemap file. When you view the project you should see a navigation tree like this:

ASP.Net TreeView XML Sitemap
ASP.Net TreeView XML Sitemap

SiteMapPath or Breadcrumb Trail

This is probably the easiest control to use for navigation, as you do not need to do anything apart from dropping it into a placeholder. Just drag the object from the toolbox to the page and build the project. When you preview the project now you will see a breadcrumb trail which will illustrate the current page and the pages higher up the hierarchy.

All of these tools can be styled using the built-in properties or through CSS classes to create a better visual experience.

Creating Custom Error Pages with ASP.Net

We have all seen the white, yellow and red "Server Error in Application" messages in ASP.Net, but there are ways of preventing this screen from showing and displaying a custom error page with a more customer-focused message.

Firstly, exception handling can be used to prevent the code from getting into a state that it cannot recover from. In the rare circumstance that an unhandled error occurs the page can be set to redirect to a custom error screen.

Server Error in Application ASP.Net Custom Errors
Server Error in Application ASP.Net Custom Errors

There is a setting in the web.config to redirect errors for remote users (if you view the page on localhost web server then you can see the error and debug the code accordingly).

C#
<customErrors defaultRedirect="myErrorPage.aspx" mode="RemoteOnly"/>

If you do not wish errors to be shown at all, not even on localhost, then set the mode to On instead of RemoteOnly.

You can also set custom error pages for specific errors that your code cannot process, for example, a 401 unauthorised, 404 Not Found page or a 500 internal error. Simply add extra lines and change the attributes to meet your needs.

C#
<customErrors mode="On">
  <error statusCode="404" redirect="/errorpages/404.aspx" />
  <error statusCode="500" redirect="/errorpages/500.aspx" />
</customErrors>

Creating User Controls in ASP.Net

User controls can encapsulate your code and HTML into smaller more functional, reusable, units which can be added to an ASP page and treated as an object.

User controls allow you to create your own set of objects and user interface controls within an ascx control file. You can then reference your new control on the asp page using tags as you would add any other control.

User controls are best suited to common elements of a web page, for example, navigation, login, headers and so on. A control can be shared among all the pages within an application, but not between applications without adding a control reference. Like asp pages, user controls are compiled on first use and cached in memory for subsequent requests to reduce response times.

To create a user control, select Add New Item from the solution explorer and select Web User Control from the list. This will create a new .ascx file in the root of the website. It's good practice to gather your controls together and store them in a separate folder within the website code.

An ascx control file is just like any other asp page, you can add server controls from the toolbox, it has a code-behind file and looks just the same in the design view and source view.

To include a user control in a host page, you can either drag the file from Solution Explorer to the design view of Visual Studio or you can use the @Register directive.

Creating a Control

Start with a new Visual Studio or Web Developer website. Using the solution explorer create a new folder called "controls" (without quotes). Right-click on it and Add New Item. Select Web User Control from the list and call it PageTitleControl.

Visual Studio will create PageTitleControl.ascx and PageTitleControl.cs for you. Add a text box and a button to the ascx page in design view and double-click on the button to activate the code editor. This control will simply change the page title to whatever is keyed into the text box.

C#
protected void Button1_Click(object sender, EventArgs e)
{
  Page.Title = TextBox1.Text;
}

Using The Control

Now go back to your Default.aspx page and switch to design view. Drag the newly created PageTitleControl.ascx onto the design view and the control will be added. If you switch to source view you will see that Visual Studio has added the following lines automatically. Notice the extra @Register tag which tells the script compiler the location of the control, tag name referrers to the name of the control and the tag prefix denotes the "library" that the script is part of. These can be customised from within the source code.

C#
<%@ Register Src="controls/PageTitleControl.ascx" TagName="<span style="background-color:yellow">PageTitleControl</span>" 
TagPrefix="<span style="background-color:lime">MyControls</span>" %>

<<span style="background-color:lime">MyControls</span>:<span style="background-color:yellow">PageTitleControl</span> ID="myPageTitleControl" runat="server" />
C#
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Src="controls/PageTitleControl.ascx" TagName="PageTitleControl" TagPrefix="MyControls" %>

<!DOCTYPE html PUBLIC "-/W3C/DTD XHTML 1.0 Transitional/EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <MyControls:PageTitleControl ID="myPageTitleControl" runat="server" />
    </div>
    </form>
</body>
</html>

Now when you build and run the project you will see a text box and button that changes the page title when you click on it.

This is only a very simple example of user controls, in reality, you will create more complex controls, which could be made of other user controls. This should give you an idea to get you started.

Tracing and Remote Debug in ASP.Net

By default, ASP.Net will show a default "Server Error in Application" message when an unhandled exception occurs, something that is not very secure but useful for debugging. If you are working on a live box this is not a very secure way of working, it is much better to log the errors and handle the problem transparently to the user. This process is Tracing.

Tracing and Remote Debug allow developers to access runtime information remotely using the trace object.

You may wish to create a custom error page for your website visitors. This will be shown instead of the default server error page. Developers can use remote debugging to analyse the problem.

During runtime, you can use the Debug and the Trace objects to output the value of variables, assert whether a condition is met, trace the execution path of the application and collect the information in a trace file.

Tracing can be configured on the page level or the application level.

Setting up Tracing

To enable page-level tracing simply add Trace="true" to the page ASP directive:

C#
<% page Language="c#" Trace="true" %>

Trace information will only be processed for the page(s) containing this flag.

Application level (every page) tracing can be enabled by enabling tracing within the web.config file located in the application root.

C#
<trace enabled="true" pageOutput="true" localOnly="true" />

When enabled the rendered page will contain a great deal of debugging information such as response headers, the time taken to execute various stages of the request, session variables, server variables, session IDs and so on. This is shown by default below the content of the page for local connections only.

You can also set the trace information to be stored within a file by setting pageOutput to false. This will store the trace information in a file located at http://server/project/trace.axd.

Trace and Debug in ASP.Net
Trace and Debug in ASP.Net

Using Trace

Writing Data to the Trace

Once trace is up and running you can write custom messages and variable dumps using the Trace object.

C#
Trace.Write("category", "message");

Where category forms a section in the log which identifies a collection of messages and the message is the text to show. You can use string.format to include variables.

Executing code only if tracing is enabled

There is a conditional that can be used to execute code if tracing is enabled, but skip over if it's not.

C#
if (Trace.IsEnabled)
{
  string strMsg = "Tracing is enabled and working";
  Trace.Write("My Trace", strMsg);
}

Programmatically Enabling/Disabling Trace

Trace can be enabled or disabled at runtime by accessing the trace object and setting the IsEnabled value.

C#
HttpContext.Current.Trace.IsEnabled = true;

Remote Debugging

Remote debugging enables web applications to be developed and debugged from outside the server. This allows for simplified team development and site management. Remote debugging requires that Visual Studio .Net or remote components be installed on the server. Visual Studio .Net must be used on the client. This is one of the few features that are not available on Express editions.

Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

We respect your privacy, and will not make your email public. Learn how your comment data is processed.