Web Design that taps into the haromny and vision of your dreams.

What Are ASP.Net Webforms

A look at ASP.Net and Microsoft's web publishing language

By on in Coding

6,615 words, estimated reading time 31 minutes.

Introduction to Programming with C# Series
  1. Introduction to Programming with C# 7
  2. C# Programming Fundamentals
  3. Introduction to Object-Oriented Programming
  4. C# Object-Oriented Programming Part 2
  5. Flow Control and Control Structures in C#
  6. C# Data Types, Variables and Casting
  7. C# Collection Types (Array, List, Dictionary, Hash Table)
  8. C# Operators
  9. Using Data in C# 7 with ADO.Net & Entity Framework
  10. LINQ: .NET Language Integrated Query
  11. Error and Exception Handling in C#
  12. Advanced C# Programming Topics
  13. Reflection in C#
  14. What Are ASP.Net Webforms
  15. Introduction to ASP.Net MVC
  16. Windows Application Development
  17. Assemblies in C#
  18. Working with Resources Files, Culture & Regions
  19. Regular Expressions in C#
  20. Introduction to XML with C#
  21. Complete Guide to File Handling in C#

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

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 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 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 on to.

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.

<%@ 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 times you don't need to change it.

The next two lines are the standard HTML doctype and html header tags. These 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:

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

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:

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

This will be rendered on the browser as:

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

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, style from a function.

Combined mode puts the C# (or Visual Basic) code at the top or bottom of the layout page and 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.

<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>
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 to 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:

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 to 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:

<%@ 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.

<%@ 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">
 <p>This is my content</p>
</asp:Content>

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

<div class="header"><h1>This is my Website Header</h1></div>
<div>
  <p>This is my content</p>
</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 completed 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 off 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!

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

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

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

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

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.

<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 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 SideClient 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 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 a number of 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:

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

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.

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

Session State requires that a session cookie be loaded onto the clients 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. In order 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.

<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:\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 of 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 value 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:

<?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 there are two sample products that 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.

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

Title Tag from XML Sitemap in Master Page

<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 <a href=""></a> style of hyperlink, but ASP.Net provides a hyperlink object which links into existing pages. This object is found within the standard items of the toolbox and is configurable from the properties window.

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

This will be rendered on the browser as

<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 in the master page and contained with a div that aligns right.

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

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

 
<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 are able to 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 in 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 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 off 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.

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 tag prefix denotes the "library" that the script is part of. These can be customised from within the source code.

 
<%@ 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" />
 
<%@ 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 allows 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:

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

<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 id's 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.

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

Where category forms a section in the log which identifies a collection of messages and 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 is it's not.

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.

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.

Last updated on: Thursday 11th October 2018

 

Comments

Have a question or suggestion? Please leave a comment to start the discussion.

 

Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.