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

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 uses 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, creating new projects using the MVC structure is highly advisable. 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.

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 page's dynamic content and HTML elements, and the code behind it 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 you use in a web form are the same controls and classes 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 migrating existing Windows applications to web-based forms and web services easier.
Test Environment
Visual Studio and Visual Web Developer both have a limited version of IIS (Internet Information Services) that can be used only for local connections. Using the loopback interface will allow you to develop and test websites and servers on a local machine. 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, the page usually contains 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 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 it is located, the class that this page inherits from and whether to assign event handlers automatically. 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 be located inside 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 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 produced on every ASP.Net page. The view state contains an encrypted name-value pair for the items on the form. This maintains the page's status when 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 is to double-click the page in the designer. This will auto-wire the onPageLoad
event. With this method, you can set up the form properties, fill in default values, and so on. One of the first things you may want is to 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 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 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 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 commonly used in PHP.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 text box's contents are shown in the label below.
Postbacks
When you submit a form to the server on the same page as the form was displayed, 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 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;
}
}
This code will 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 or 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 and the master page.
You should notice that the master page contains all the HTML header and body tags. A ContentPlaceHolder is between the body tag. 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 but 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:content placeholder 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". It 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">
This is my content
</asp:Content>
The result when requesting default2.aspx from the server is:
<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>
I have set the title to "My Page" in the content page, and ASP.Net intercepts this, 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, found in the toolbox's Validation section.
We will start with a basic form that asks for a name and a telephone number. It's a simple form, but we are not attending 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 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 cannot 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, 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 properties 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. The error message will be displayed if less than four or more than four are entered.
Using Multiple Validators
You can use multiple validation objects on a control; add them to the form, set them up and assign the ControlToValidate property. You will notice the position of the controls relative to the position on the form.

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

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.

Managing Session State in ASP.Net
HTTP is a stateless protocol, meaning that each request is processed as it comes; after the request has been processed, all data is discarded. No state is maintained across requests, even from the same client.
ASP.Net provides a set of functionalities that the client or the server can use to maintain a state.
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 hello.aspx is aware of the data entered in a managed state environment.

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 requested on each page. |
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 the state of 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 disabled. If a client has turned off cookies, then the session state cannot be maintained using this method, and you should use query strings instead.
Query Strings (cookieless)
If cookies cannot store the SessionID, query strings must be used instead. This involved storing the session ID within the URL of the requested page. 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 query strings, including search engines, duplicate URLs, and the possibility of tampering with session ID. 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
The application state is a global storage mechanism that is 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
The session state is a storage mechanism accessible to 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 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.
You need to change the sessionState section of the web.config file to enable state servers.
<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 stores 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 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, on 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, which will be used for some navigation items and page titles.
Sitemaps
Sitemaps are XML format documents the navigation controls use to allow for navigation between pages. This Microsoft proprietary format should not be confused with a Google XML Sitemap. The role of the sitemap is to inform ASP.Net how the site pages 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 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 will use the title property to specify the page title, and on the content page, I will 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="">
style of the hyperlink, but ASP.Net provides a hyperlink object which links to existing pages. This object is within the toolbox's standard items and 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 on the master page and attached it with a div that aligns with the 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 links the TreeView and the web.sitemap file. When you view the project, you should see a navigation tree like this:

SiteMapPath or Breadcrumb Trail
This is the easiest control 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 illustrating the current page and the pages higher up the hierarchy.
These tools can be styled using the built-in properties or 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 prevent the code from getting into a state 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.

There is a setting in the web.config to redirect errors for remote users (if you view the page on the localhost web server, 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, not even on localhost, set the mode to On instead of RemoteOnly.
You can also set custom error pages for specific errors your code cannot process, such as a 401 unauthorised, 404 Not Found page or a 500 internal error. 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 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 best suit common web page elements, such as navigation, login, headers, etc. 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 and store your controls 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 the same in the design and source views.
To include a user control in a host page, you can drag the file from Solution Explorer to the design view of Visual Studio or 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 the design view, and double-click on the button to activate the code editor. This control will 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
Return 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; the tag name refers 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.
<%@ 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>
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 a very simple example of user controls; in reality, you will create more complex controls that 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, which 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 can 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, 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 much debugging information, such as response headers, the time taken to execute various request stages, session variables, server variables, session IDs, etc. This is shown below the page's content 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 at http://server/project/trace.axd.
Using Trace
Writing Data to the Trace
Once the trace runs, you can write custom messages and variable dumps using the Trace object.
Trace.Write("category", "message");
A category forms a section in the log that identifies a collection of messages; the message is the text to show. You can use string.format to include variables.
Executing code only if tracing is enabled
A conditional can be used to execute code if tracing is enabled, but skip over if 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 turned off 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 not available on Express editions.