ASP.NET

99
Table of Contents What is ASP.Net?....................................................3 ASP.Net Web Forms Model:............................................4 ASP.NET - Environment Setup.........................................4 The Visual Studio IDE:............................................4 Ways to work with views and windows:..............................5 Adding folders and files to your web site:........................6 Projects and Solutions:...........................................6 Building and Running a Project:...................................7 ASP.NET - Life Cycle................................................7 Background........................................................7 When the Page is requested for the first time.....................8 Life cycle when the page processed during a postback event........9 ASP.NET - First Example............................................11 Page directives:.................................................11 Code Section:....................................................11 Page Layout:.....................................................11 Using Visual Studio IDE:.........................................12 ASP.NET - Event Handling...........................................14 What is an Event?................................................14 Event Arguments:.................................................14 Application and Session Events:..................................14 Page and Control Events:.........................................15 Event Handling Using Controls:...................................15 Default Events:..................................................16 Example:.........................................................17 ASP.NET – Controls.................................................18 Properties of the Server Controls................................19

description

Santosh Khuray(Irving tx)

Transcript of ASP.NET

Page 1: ASP.NET

Table of ContentsWhat is ASP.Net?.....................................................................................................................................3

ASP.Net Web Forms Model:.....................................................................................................................4

ASP.NET - Environment Setup.................................................................................................................4

The Visual Studio IDE:..........................................................................................................................4

Ways to work with views and windows:..............................................................................................5

Adding folders and files to your web site:...........................................................................................6

Projects and Solutions:........................................................................................................................6

Building and Running a Project:...........................................................................................................7

ASP.NET - Life Cycle.................................................................................................................................7

Background..........................................................................................................................................7

When the Page is requested for the first time.....................................................................................8

Life cycle when the page processed during a postback event.............................................................9

ASP.NET - First Example.........................................................................................................................11

Page directives:..................................................................................................................................11

Code Section:.....................................................................................................................................11

Page Layout:......................................................................................................................................11

Using Visual Studio IDE:.....................................................................................................................12

ASP.NET - Event Handling......................................................................................................................14

What is an Event?..............................................................................................................................14

Event Arguments:..............................................................................................................................14

Application and Session Events:.........................................................................................................14

Page and Control Events:...................................................................................................................15

Event Handling Using Controls:..........................................................................................................15

Default Events:...................................................................................................................................16

Example:............................................................................................................................................17

ASP.NET – Controls................................................................................................................................18

Properties of the Server Controls......................................................................................................19

Methods of the Server Controls.........................................................................................................21

Example:............................................................................................................................................23

Page 2: ASP.NET

UserControls - Introduction...................................................................................................................26

Creating a UserControl......................................................................................................................27

Using a UserControl...........................................................................................................................28

Loading dynamically..........................................................................................................................29

Events in UserControls.......................................................................................................................30

Validation...............................................................................................................................................32

Introduction.......................................................................................................................................32

RequiredFieldValidator......................................................................................................................33

CompareValidator..............................................................................................................................34

RangeValidator..................................................................................................................................35

RegularExpressionValidator...............................................................................................................36

CustomValidator................................................................................................................................37

More validation.................................................................................................................................38

Caching..................................................................................................................................................39

Introduction.......................................................................................................................................39

OutputCache......................................................................................................................................39

OutputCache - more examples..........................................................................................................40

OutputCache - Substitution...............................................................................................................41

Caching objects..................................................................................................................................42

Cookies..................................................................................................................................................43

Sessions.................................................................................................................................................46

Turning Off Session State...................................................................................................................50

Storing Session State InProc..............................................................................................................50

Storing Session State in a State Server...............................................................................................51

Storing Session State in a Database...................................................................................................52

ViewState..............................................................................................................................................52

Using the Web.config............................................................................................................................54

Authentication and Authorization in ASP.NET.......................................................................................56

Authentication in ASP.NET.................................................................................................................56

Authentication providers...................................................................................................................57

Windows authentication and IIS........................................................................................................58

Passport authentication.....................................................................................................................59

Page 3: ASP.NET

Forms authentication........................................................................................................................59

Configuring Authorization..................................................................................................................59

Best practices....................................................................................................................................60

Master Pages.........................................................................................................................................61

Uses of Master Pages........................................................................................................................61

Terminology.......................................................................................................................................61

Creating a MasterPage......................................................................................................................61

Adding the ContentPages..................................................................................................................64

Changing the Master Page's Properties from Content Pages............................................................65

Changing the Master Page Dynamically.............................................................................................67

Custom Server Control..........................................................................................................................69

Themes and Skins in ASP.NET................................................................................................................77

Using ASP.NET 2.0 Packaged Themes......................................................................................77

What is ASP.Net?

ASP.Net is a web development platform, which provides a programming model, a comprehensive software infrastructure and various services required to build up robust web application for PC, as well as mobile devices.

ASP.Net works on top of the HTTP protocol and uses the HTTP commands and policies to set a browser-to-server two-way communication and cooperation.

ASP.Net is a part of Microsoft .Net platform. ASP.Net applications are complied codes, written using the extensible and reusable components or objects present in .Net framework. These codes can use the entire hierarchy of classes in .Net framework.

The ASP.Net application codes could be written in either of the following languages:

C# Visual Basic .Net

Jscript

J#

Page 4: ASP.NET

ASP.Net is used to produce interactive, data-driven web applications over the internet. It consists of a large number of controls like text boxes, buttons and labels for assembling, configuring and manipulating code to create HTML pages.

ASP.Net Web Forms Model:

ASP.Net web forms extend the event-driven model of interaction to the web applications. The browser submits a web form to the web server and the server returns a full markup page or HTML page in response.

All client side user activities are forwarded to the server for stateful processing. The server processes the output of the client actions and triggers the reactions.

Now, HTTP is a stateless protocol. ASP.Net framework helps in storing the information regarding the state of the application, which consists of:

Page state Session state

The page state is the state of the client, i.e., the content of various input fields in the web form. The session state is the collective obtained from various pages the user visited and worked with, i.e., the overall session state. To clear the concept, let us take up an example of a shopping cart as follows.

User adds items to a shopping cart. Items are selected from a page, say the items page, and the total collected items and price are shown in a different page, say the cart page. Only HTTP cannot keep track of all the information coming from various pages. ASP.Net session state and server side infrastructure keeps track of the information collected globally over a session.

The ASP.Net runtime carries the page state to and from the server across page requests while generating the ASP.Net runtime codes and incorporates the state of the server side components in hidden fields.

This way the server becomes aware of the overall application state and operates in a two-tiered connected way.

ASP.NET - Environment Setup

ASP.Net provides an abstraction layer on top of HTTP on which the web applications are built. It provides high-level entities like classes and components within an object-oriented paradigm.

The key development tool for building ASP.Net applications and front ends is Visual Studio. In these tutorials, we will work on Visual Studio 2008.

Visual Studio is an integrated development environment for writing, compiling and debugging the code. It provides a complete set of development tools for building ASP.Net web applications, web services, desktop applications and mobile applications.

The Visual Studio IDE:

The new project window allows choosing an application template from the available templates.

Page 5: ASP.NET

When you start a new web site, ASP.NET provides the starting folders and files for the site, including two files for the first web form of the site.

The file named Default.aspx contains the HTML and asp code that defines the form, and the file named Default.aspx.cs (for C# coding) or the file named Default.aspx.vb (for vb coding) contains the code in the language you have chosen and this code is responsible for the form's works.

The primary window in the Visual Studio IDE is the Web Forms Designer window. Other supporting windows are the Toolbox, the Solution Explorer, and the Properties window. You use the designer to design a web form, to add code to the control on the form so that the form works according to your need, you use the code editor.

Ways to work with views and windows:

The following are the ways to work with different windows:

To change the Web Forms Designer from one view to another, click on the Design or source button. To close a window, click on the close button on the upper right corner and to redisplay, select it from

the View menu.

To hide a window, click on its Auto Hide button; the window changes into a tab, to redisplay again click on the Auto Hide button again.

To size a wind just drag it.

Page 6: ASP.NET

Adding folders and files to your web site:

When a new web form is created, Visual Studio automatically generates the starting HTML for the form and displays it in Source view of the web forms designer. The Solution Explorer is used to add any other files, folders or any existing item on the web site.

To add a standard folder, right-click on the project or folder under which you are going to add the folder in the Solution Explorer and choose New Folder.

To add an ASP.Net folder, right-click on the project in the Solution Explorer and select the folder from the list.

To add an existing item to the site, right-click on the project or folder under which you are going to add the item in the Solution Explorer and select from the dialog box.

Projects and Solutions:

A typical ASP.Net application consists of many items: the web content files (.aspx), source files (e.g., the .cs files), assemblies (e.g., the .dll files and .exe files), data source files (e.g., .mdb files), references, icons, user controls and miscellaneous other files and folders. All these files that make up the website are contained in a Solution.

When a new website is created VB2008 automatically creates the solution and displays it in the solution explorer.

Solutions may contain one or more projects. A project contains content files, source files, and other files like data sources and image files. Generally the contents of a project are compiled into an assembly as an executable file (.exe) or a dynamic link library (.dll) file.

Typically a project contains the following content files:

Page file (.aspx) User control (.ascx)

Web service (.asmx)

Page 7: ASP.NET

Master page (.master)

Site map (.sitemap)

Website configuration file (.config)

Building and Running a Project:

The application is run by selecting either Start or Start Without Debugging from the Debug menu, or by pressing F5 or Ctrl-F5. The program is built i.e. the .exe or the .dll files are generated by selecting a command from the Build menu.

ASP.NET - Life Cycle

ASP.Net life cycle specifies, how:

ASP.Net processes pages to produce dynamic output The application and its pages are instantiated and processed

ASP.Net compiles the pages dynamically

Background

IIS: It is the default web server with Microsoft .NET. Internet Information Server helps to deploy web sites/web application. IIS web server receives requests for a web resource (file), it checks the extension of the file (e.g. .aspx, .ascx, .ashx and .asmx) and then it determines which ISAPI extension should handle this request and passes this request to proper ISAPI extension.

ASPNET_ISAPI.DLL: IIS loads this DLL and sends the page request to this DLL. This DLL loads the HTTPRuntime for further processing.

ASPNET_WP.EXE: It contains an Application Pool. Each Application Pool can contain any number of Applications. Application Pool is also called as AppDomain. When a web page is requested, IIS looks for the application pool under which the current application is running and forwards the request to the respective worker process.

A page in an ASP.NET application consists of several server controls. These are the fundamental building blocks of an ASP.NET application. The Life cycle of an ASP.NET page, depends on whether the page is requested for the first time or it is a postback. Postback is a process by which a page can request for itself.

Table Showing Stage and Corresponding Events

Stage Events/Method

Initialization of the page Page_Init

Page 8: ASP.NET

Stage Events/Method

Loading of the View State LoadViewState

Processing of the Postback data LoadPostData

Loading of Page Page_Load

Notification of PostBack RaisePostDataChangedEvent

Handling of PostBack Event RaisePostBackEvent

Pre Rendering of Page Page_PreRender

Saving of view state SaveViewState

Rendering of Page Page_Render

Unloading of the Page Page_UnLoad

When the Page is requested for the first time

The Life Cycle of a page when requested for the first time:

Initializing: During this phase, the server creates an instance of the server control

Loading: During this phase, the instance of the control is loaded onto the page object in which it is defined.

PreRendering: In this event, Page ensures that all child controls are created. Page calls EnsureChildControls for all controls, including itself. Every control whose datasource/databind property is set calls for its databind method.

Saving: During this phase, the state information of the control is saved. For example, if a value is set for the control during the Load event, it is embedded in the HTML tag that will be returned to the browser.

Rendering: During this phase, the server creates the corresponding HTML tag for the control.

Disposing: During this phase, all cleanup tasks, such as closing files and database connections opened by the control are performed.

Page 9: ASP.NET

Unloading: During this phase, all cleanup tasks, such as destroying the instances of server control are performed. This is the final event in the life cycle of a server control

Life cycle when the page processed during a postback eventThe processing sequence in which a page is processed during a postback event is:

Initializing: During this phase, the server creates an instance of the server control

Loading view state: During this phase, the view state of the control posted by the client is reloaded into the new instance of the control.

Loading: During this phase, the instance of the control is loaded onto the page object in which it is defined.

Loading the postback data: During this phase, the server searches any data corresponding to the control that is loaded in the data posted by the client.

PreRendering: During this phase, the control is updated with the changes made to it. This prepares the control for rendering.

Saving state: During this phase, the change in the state of control between the current request and the previous request of the page is saved. For each change, the corresponding event is raised. For example, if the text of a textbox is changed, the new text is saved and a text_change event is raised.

Rendering: During this phase, the server creates the corresponding HTML tag for the control.

Disposing: During this phase, all cleanup tasks, such as closing files and database connections opened by the control are performed.

Unloading: During this phase, all cleanup tasks, such as destroying the instances of server control are performed. This is the final event in the life cycle of a server control

The events associated with the relevant page cycle phases are:

Page Initialization: Page_Init View State Loading:LoadViewState

Postback data processing: LoadPostData

Page Loading: Page_Load

PostBack Change Notification: RaisePostDataChangedEvent

PostBack Event Handling: RaisePostBackEvent

Page Pre Rendering Phase: Page_PreRender

View State Saving: SaveViewState

Page Rendering: Page_Render

Page Unloading: Page_UnLoad

Page 10: ASP.NET

The following figure illustrates how the server controls on an ASP.NET page is processed by the server:

Page 11: ASP.NET

ASP.NET - First Example

An ASP.Net page is made of number of server controls along with the HTML controls, text and images. Sensitive data from the page and the states of different controls on the page are stored in hidden fields and forms the context of that page request.

ASP.Net runtime controls all association between a page instance and its state. An ASP.Net page is an object of the Page Class or inherited from it.

All the controls on the pages are also objects of the related control class inherited from a parent Control class. When a page is run an instance of the page object is created along with all its content controls.

An ASP.Net page is also a server side file saved with the .aspx extension. It is modular in nature and can be divided into the following core sections:

Page directives Code Section

Page Layout

Page directives:

The page directives set up the environments for the page to run. The @Page directive defines page-specific attributes used by the ASP.Net page parser and compiler. Page directives specify how the page should be processed, and which assumptions are to be taken about the page.

It allows importing namespaces, loading assemblies and registering new controls with custom tag names and namespace prefixes. We will discuss all of these concepts in due time.

Code Section:

The code section provides the handlers for the page and control events along with other functions required. We mentioned that, ASP.Net follows an object model. Now, these objects raises events when something happens on the user interface, like a user clicks a button or moves the cursor. How these events should be handled? That code is provided in the event handlers of the controls, which are nothing but functions bound to the controls.

The code section or the code behind file provides all these event handler routines, and other functions used by the developer. The page code could be precompiled and deployed in the form of a binary assembly.

Page Layout:

The page layout provides the interface of the page. It contains the server controls, text, inline JavaScript and HTML tags:

The following code snippet provides a sample ASP.Net page explaining pafe directives, code section and page layout written in C#:

<!-- directives --><% @Page Language="C#" %>

<!-- code section --><script runat="server">private void convertoupper(object sender, EventArgs e)

Page 12: ASP.NET

{string str = mytext.Value;changed_text.InnerHtml = str.ToUpper();

}</script>

<!-- Layout --><html><head> <title> Change to Upper Case </title> </head><body><h3> Conversion to Upper Case </h3><form runat="server">

<input runat="server" id="mytext" type="text" /><input runat="server" id="button1" type="submit"

value="Enter..." OnServerClick="convertoupper"/><hr /><h3> Results: </h3><span runat="server" id="changed_text" /></form></body></html>

Copy this file to the web server's root directory. Generally it is c:\inetput\wwwroot. Open the file from the browser to run it and it should generate following result:

Using Visual Studio IDE:

Let us develop the same example using Visual Studio IDE. Instead of typing the code, you can just drag the controls into the design view:

Page 13: ASP.NET

The content file is automatically developed. All you need to add is the Button1_Click routine, which is as follows:

protected void Button1_Click(object sender, EventArgs e){ string buf = TextBox1.Text; changed_text.InnerHtml = buf.ToUpper();}

The content file code is:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="firstexample._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> <asp:TextBox ID="TextBox1" runat="server" Width="224px"> </asp:TextBox> <br /> <br /> <asp:Button ID="Button1" runat="server" Text="Enter..." Width="85px" onclick="Button1_Click" /> <hr /> <h3> Results: </h3> <span runat="server" id="changed_text" /> </div> </form></body></html>

Run the example either from Debug menu, or by pressing Ctrl-F5 or by right clicking on the design view and choosing 'View in Browser' from the popup menu. This should generate following result:

Page 14: ASP.NET

ASP.NET - Event Handling

What is an Event?

Event is an action or occurrence like mouse click, key press, mouse movements, or any system generated notification. The processes communicate through events. For example, Interrupts are system generated events. When events occur the application should be able to respond to it.

In ASP.Net an event is raised on the client, and handled in the server. For example, a user clicks a button displayed in the browser. A Click event is raised. The browser handles this client-side event by posting it to the server.

The server has a subroutine describing what to do when the event is raised; it is called the event-handler. Therefore, when the event message is transmitted to the server, it checks whether the Click event has an associated event handler, and if it has, the event handler is executed.

Event Arguments:

ASP.Net event handlers generally take two parameters and return void. The first parameter represents the object raising the event and the second parameter is called the event argument.

The general syntax of an event is:

private void EventName (object sender, EventArgs e);

Application and Session Events:

The most important application events are:

Application_Start . it is raised when the application/website is started Application_End . it is raised when the application/website is stopped

Similarly, the most used Session events are:

Session_Start . it is raised when a user first requests a page from the application Session_End . it is raised when the session ends

Page 15: ASP.NET

Page and Control Events:

Common page and control events are:

DataBinding . raised when a control bind to a data source Disposed . when the page or the control is released

Error . it is an page event, occurs when an unhandled exception is thrown

Init . raised when the page or the control is initialized

Load . raised when the page or a control is loaded

PreRender . raised when the page or the control is to be rendered

Unload . raised when the page or control is unloaded from memory

Event Handling Using Controls:

All ASP.Net controls are implemented as classes, and they have events which are fired when user performs certain action on them. For example, when a user clicks a button the 'Click' event is generated. For handling these events there are in-built attributes and event handlers. To respond to an event, the event handler is coded.

By default Visual Studio creates an event handler by including a Handles clause on the Sub procedure. This clause names the control and event that the procedure handles.

The asp tag for a button control:

<asp:Button ID="btnCancel" runat="server" Text="Cancel" />

The event handler for the Click event:

Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.ClickEnd Sub

An event can also be coded without a Handles clause. Then the handler must be named according to the appropriate event attribute of the control.

The asp tag for a button control:

<asp:Button ID="btnCancel" runat="server" Text="Cancel" Onclick="btnCancel_Click" />

The event handler for the Click event:

Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs)End Sub

Page 16: ASP.NET

The common control events are:

Event Attribute Controls

Click OnClick Button, image button, link button, image map

Command OnCommand Button, image button, link button

TextChanged OnTextChanged Text box

SelectedIndexChanged OnSelectedIndexChanged

Drop-down list, list box, radio button list, check box list.

CheckedChanged OnCheckedChanged Check box, radio button

Some events cause the form to be posted back to the server immediately, these are called the postback events. For example, the click events like, Button.Click. Some events are not posted back to the server immediately, these are called non-postback events.

For example, the change events or selection events, such as, TextBox.TextChanged or CheckBox.CheckedChanged. The nonpostback events could be made to post back immediately by setting their AutoPostBack property to true.

Default Events:

The default event for the Page object is the Load event. Similarly every control has a default event. For example, default event for the button control is the Click event.

The default event handler could be created in Visual Studio, just by double clicking the control in design view. The following table shows some of the default events for common controls:

Control Default Event

AdRotator AdCreated

BulletedList Click

Button Click

Calender SelectionChanged

CheckBox CheckedChanged

CheckBoxList SelectedIndexChanged

DataGrid SelectedIndexChanged

DataList SelectedIndexChanged

DropDownList SelectedIndexChanged

HyperLink Click

ImageButton Click

ImageMap Click

LinkButton Click

ListBox SelectedIndexChanged

Menu MenuItemClick

Page 17: ASP.NET

RadioButton CheckedChanged

RadioButtonList SelectedIndexChanged

Example:

This example has a simple page with a label control and a button control on it. As the page events like, Page_Load, Page_Init, Page_PreRender etc. takes place, it sends a message, which is displayed by the label control. When the button is clicked, the Button_Click event is raised and that also sends a message to be displayed on the label.

Create a new website and drag a label control and a button control on it from the control tool box. Using the properties window, set the IDs of the controls as .lblmessage. and .btnclick. respectively. Set the Text property of the Button control as 'Click'.

The markup file (.aspx):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="eventdemo._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> <asp:Label ID="lblmessage" runat="server" > </asp:Label> <br /> <br /> <br /> <asp:Button ID="btnclick" runat="server" Text="Click" onclick="btnclick_Click" /> </div> </form></body></html>

Double click on the design view to move to the code behind file. The Page_Load event is automatically created without any code in it. Write down the following self-explanatory code lines:

using System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;

Page 18: ASP.NET

using System.Xml.Linq;

namespace eventdemo{public partial class _Default : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { lblmessage.Text += "Page load event handled. <br />"; if (Page.IsPostBack) { lblmessage.Text += "Page post back event handled.<br/>"; } } protected void Page_Init(object sender, EventArgs e) { lblmessage.Text += "Page initialization event handled.<br/>"; } protected void Page_PreRender(object sender, EventArgs e) { lblmessage.Text += "Page prerender event handled. <br/>"; } protected void btnclick_Click(object sender, EventArgs e) { lblmessage.Text += "Button click event handled. <br/>"; } }}

Run the page. The label shows page load, page initialization and the page pre-render events. Click the button to see effect:

Page 19: ASP.NET

ASP.NET – Controls

Controls are small building blocks of the graphical user interface, which includes text boxes, buttons, check boxes, list boxes, labels and numerous other tools, using which users can enter data, make selections and indicate their preferences.

Controls are also used for structural jobs, like validation, data access, security, creating master pages, data manipulation.

ASP.Net uses five types of web controls, which are:

HTML controls HTML Server controls

ASP.Net Server controls

ASP.Net Ajax Server controls

User controls and custom controls

ASP.Net server controls are the primary controls used in ASP.Net. These controls again could be grouped into the following categories:

Validation controls - these are used to validate user input and work by running client-side script Data source controls - these controls provides data binding to different data sources

Data view controls - these are various lists and tables, which can bind to data from data sources for display

Personalization controls - these are used for personalization of a page according to the user's preference, based on user information

Login and security controls - these controls provide user authentication

Master pages - these provides consistent layout and interface throughout the application

Navigation controls - these helps in navigation, for example, the menus, tree view etc.

Rich controls - these implements special features, for example, AdRotator control, FileUpload control, Calendar control etc.

The basic syntax for using server controls is:

<asp:controlType ID ="ControlID" runat="server" Property1=value1 [Property2=value2] />

However, visual studio has the following features, which helps in error free coding:

Dragging and dropping of controls in design view IntelliSense feature that displays and auto-completes the properties

The properties window to set the property values directly

Page 20: ASP.NET

Properties of the Server Controls

The ASP.Net server controls with a visual aspect are derived from the WebControl class and inherit all the properties, events and methods of this class.

The WebControl class itself and some other server controls that are not visually rendered, e.g., the PlaceHolder control or XML control etc., are derived from the System.Web.UI.Control class.

ASP.Net server controls inherit all properties, events and methods of the WebControl and System.Web.UI.Control class.

The following table shows the inherited properties, which are common to all server controls:

Property Description

AccessKey Pressing this key with the Alt key moves focus to the control

Attributes It's the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.

BackColor Background colour.

BindingContainer The control that contains this control's data binding.

BorderColor Border colour.

BorderStyle Border style.

BorderWidth Border width.

CausesValidation Indicates if it causes validation.

ChildControlCreated It indicates whether the server control's child controls have been created.

ClientID Control ID for HTML markup.

Context The HttpContext object associated with the server control.

Controls Collection of all controls contained within the control

ControlStyle The style of the Web server control.

CssClass CSS class

DataItemContainer Gets a reference to the naming container if the naming container implements IDataItemContainer.

DataKeysContainer Gets a reference to the naming container if the naming container implements IDataKeysControl.

DesignMode It indicates whether the control is being used on a design surface.

DisabledCssClass Gets or sets the CSS class to apply to the rendered HTML element when the control is disabled.

Enabled Indicates whether the control is grayed out

EnableTheming Indicates whether theming applies to the control.

EnableViewState Indicates whether the view state of the control is maintained.

Events Gets a list of event handler delegates for the control.

Font Font .

Page 21: ASP.NET

Forecolor Foreground colour.

HasAttributes Indicates whether the control has attributes set.

HasChildViewState indicates whether the current server control's child controls have any saved view-state settings.

Height Height in pixels or %.

ID Identifier for the control.

IsChildControlStateCleared Indicates whether controls contained within this control have control state.

IsEnabled Gets a value indicating whether the control is enabled

IsTrackingViewState It indicates whether the server control is saving changes to its view state.

IsViewStateEnabled It indicates whether view state is enabled for this control.

LoadViewStateById It indicates whether the control participates in loading its view state by ID instead of index.

Page Page containing the control.

Parent Parent control.

RenderingCompatibility It specifies the ASP.NET version that rendered HTML will be compatible with.

Site The container that hosts the current control when rendered on a design surface.

SkinID Gets or sets the skin to apply to the control. (

Style Gets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control.

TabIndex Gets or sets the tab index of the Web server control.

TagKey Gets the HtmlTextWriterTag value that corresponds to this Web server control.

TagName Gets the name of the control tag.

TemplateControl The template that contains this control.

TemplateSourceDirectory Gets the virtual directory of the Page or control containing this control.

ToolTip Gets or sets the text displayed when the mouse pointer hovers over the Web server control.

UniqueID Unique identifier

ViewState Gets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page.

ViewStateIgnoreCase It indicates whether the StateBag object is case-insensitive.

ViewStateMode Gets or sets the view-state mode of this control.

Visible It indicates whether a server control is visible.

Width Gets or sets the width of the Web server control.

Page 22: ASP.NET

Methods of the Server Controls

The following table provides the methods of the server controls:

Method Description

AddAttributesToRender Adds HTML attributes and styles that need to be rendered to the specified HtmlTextWriterTag.

AddedControl Called after a child control is added to the Controls collection of the Control object.

AddParsedSubObject Notifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control's control collection.

ApplyStyleSheetSkin Applies the style properties defined in the page style sheet to the control.

ClearCachedClientID Infrastructure. Sets the cached ClientID value to null.

ClearChildControlState Deletes the control-state information for the server control's child controls.

ClearChildState Deletes the view-state and control-state information for all the server control's child controls.

ClearChildViewState Deletes the view-state information for all the server control's child controls.

CreateChildControls Used in creating child controls.

CreateControlCollection Creates a new ControlCollection object to hold the child controls.

CreateControlStyle Creates the style object that is used to implement all style related properties.

DataBind Binds a data source to the server control and all its child controls.

DataBind(Boolean) Binds a data source to the server control and all its child controls with an option to raise the DataBinding event.

DataBindChildren Binds a data source to the server control's child controls.

Dispose Enables a server control to perform final clean up before it is released from memory.

EnsureChildControls Determines whether the server control contains child controls. If it does not, it creates child controls.

EnsureID Creates an identifier for controls that do not have an identifier.

Equals(Object) Determines whether the specified Object is equal to the current Object.

Finalize Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.

FindControl(String) Searches the current naming container for a server control with the specified id parameter.

FindControl(String, Int32) Searches the current naming container for a server control with the specified id and an integer

Focus Sets input focus to a control.

GetDesignModeState Gets design-time data for a control.

GetType Gets the Type of the current instance.

GetUniqueIDRelativeTo Returns the prefixed portion of the UniqueID property of the specified

Page 23: ASP.NET

control.

HasControls Determines if the server control contains any child controls.

HasEvents Indicates whether events are registered for the control or any child controls.

IsLiteralContent Determines if the server control holds only literal content.

LoadControlState Restores control-state information.

LoadViewState Restores view-state information.

MapPathSecure Retrieves the physical path that a virtual path, either absolute or relative, maps to.

MemberwiseClone Creates a shallow copy of the current object.

MergeStyle Copies any nonblank elements of the specified style to the Web control, but will not overwrite any existing style elements of the control.

OnBubbleEvent Determines whether the event for the server control is passed up the page's UI server control hierarchy.

OnDataBinding Raises the data binding event.

OnInit Raises the Init event.

OnLoad Raises the Load event.

OnPreRender Raises the PreRender event.

OnUnload Raises the Unload event.

OpenFile Gets a Stream used to read a file

RemovedControl Called after a child control is removed from the Controls collection of the Control object.

Render Renders the control to the specified HTML writer.

RenderBeginTag Renders the HTML opening tag of the control to the specified writer.

RenderChildren Outputs the content of a server control's children to a provided HtmlTextWriter object, which writes the content to be rendered on the client.

RenderContents Renders the contents of the control to the specified writer.

RenderControl(HtmlTextWriter)

Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled.

RenderEndTag Renders the HTML closing tag of the control into the specified writer.

ResolveAdapter Gets the control adapter responsible for rendering the specified control.

SaveControlState Saves any server control state changes that have occurred since the time the page was posted back to the server.

SaveViewState Saves any state that was modified after the TrackViewState method was invoked.

SetDesignModeState Sets design-time data for a control.

ToString Returns a String that represents the current object.

TrackViewState Causes the control to track changes to its view state so they can be stored in the object's view state property.

Page 24: ASP.NET

Example:

Let us look at a particular server control - a tree view control. A Tree view control comes under navigation controls. Other Navigation controls are: Menu control and SiteMapPath control.

Add a tree view control on the page. Select Edit Nodes... from the tasks. Edit each of the nodes using the Tree view node editor:

Once you have created the nodes, it looks like the following in design view:

The AutoFormat... task allows you to format the tree view:

Page 25: ASP.NET

Add a label control and a text box control on the page and name them lblmessage and txtmessage respectively.

Write few lines of code to ensure that when a particular node is selected, the label control displays the node text and the text box displays all child nodes under it, if any. The code behind file should look like this:

using System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq; namespace eventdemo{ public partial class treeviewdemo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { txtmessage.Text = " "; } protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e) { txtmessage.Text = " "; lblmessage.Text = "Selected node changed to: " + TreeView1.SelectedNode.Text; TreeNodeCollection childnodes = TreeView1.SelectedNode.ChildNodes; if(childnodes != null) {

Page 26: ASP.NET

txtmessage.Text = " "; foreach (TreeNode t in childnodes) { txtmessage.Text += t.Value; } } } }}

Run the page to see the effects. You will be able to expand and control the nodes.

UserControls - IntroductionA UserControl is a separate, reusable part of a page. You can put a piece of a page in a UserControl, and then reuse it from a different location. The name, UserControl, might seem a bit fancy, but actually, it's just like a regular page, with an optional CodeBehind file. A notable difference is that UserControls can be included on multiple pages, while a page can't. UserControls are used much like regular server controls, and they can be added to a page declaratively, just like server controls can. 

A big advantage of the UserControl is that it can be cached, using the OutputCache functionality, so instead of caching an entire page, you may cache only the UserControl, so that the rest of the page is still re-loaded on each request. 

An example where a UserControl could come in handy, is a control for showing information about a certain user on a community website. In the next couple of

Page 27: ASP.NET

chapters, we will create a UserControl from scratch, make it fit to our purpose, and then use it on a page. 

Creating a UserControlOkay, so we will be building a UserControl for displaying information about a community user. First of all, let's add a UserControl to our project. In your Visual Studio or Visual Web Developer, you should be able to right click on your project and select Add new item. A dialog will pop up, and you should select the Web User Control from the list of possible things to add. Let's call our UserControl UserInfoBoxControl, with the filename of UserInfoBoxControl.ascx.

You should now have a UserInfoBoxControl.ascx and a UserInfoBoxControl.ascx.cs in your project. The first is where we put our markup, and the second is our CodeBehind file. Now, if UserInfoBoxControl.ascx is not already open and selected, do so now. You will see only one line of code, the UserControl declaration. As mentioned, this control will be displaying information about a user, so let's get started adding some markup to do so:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserInfoBoxControl.ascx.cs" Inherits="UserInfoBoxControl" %>

<b>Information about <%= this.UserName %></b>

<br /><br />

<%= this.UserName %> is <%= this.UserAge %> years old and lives in <%= this.UserCountry %>

As you can see, it's all very basic. We have a declaration, some standard tags, some text, and then we have some sort of variables. Now, where do they come from? Well, right now, they come from nowhere, since we haven't declared them yet. We better do that right away. Open the CodeBehind file for the UserControl, that is, the one which ends on .cs. 

As you can see, it looks just like a CodeBehind file for a regular page, except that it inherits from UserControl instead of from Page. We will declare the three properties used in our markup, and base them on three corresponding fields.

private string userName;

private int userAge;

private string userCountry;

public string UserName

{

Page 28: ASP.NET

get { return userName; }

set { userName = value; }

}

public int UserAge

{

get { return userAge; }

set { userAge = value; }

}

public string UserCountry

{

get { return userCountry; }

set { userCountry = value; }

}

It's all very simple and works just like a regular class. You can even add methods, if you feel like it! Our UserControl is actually done now, but as you may have already experienced, we can't use it yet. A UserControl can't be displayed directly in the browser - it has to be included on a page.

Using a UserControlIn the above section, we created a UserControl, and now we will try using it for the first time. Pick a page in your project, or simply create a new one for the purpose, and open it. The first thing we have to do, is declare our UserControl. It can be done either in each page where it's used, or globally in the web.config file. There is no performance difference, but when declaring UserControls in the web.config file, the controls have to reside in a different directory than the page(s) using it. For now, let's just declare it within the page. Add the following line below the standard page declaration:

<%@ Register TagPrefix="My" TagName="UserInfoBoxControl" Src="~/UserInfoBoxControl.ascx" %>

Page 29: ASP.NET

Make sure that the Src value matches the path to your UserControl file. Now you may use the UserControl in your page, like any other control. For instance, like this:

<My:UserInfoBoxControl runat="server" ID="MyUserInfoBoxControl" />

If you look at the page now, you will see our UserControl in action, although the information will be a bit... limited. We will have to set a value for the properties we defined, for things to get just a bit more interestingly. Fortunately, it's very easy:

<My:UserInfoBoxControl runat="server" ID="MyUserInfoBoxControl" UserName="John Doe" UserAge="45" UserCountry="Australia" />

You see, every public or protected member can be accessed declaretively, allowing easy access to them when we use our control. However, with this specific UserControl, chances are that you will be receiving the information from an external resource, like a database, and then populating the UserControl from there. This usually involves the CodeBehind of the page, so how can we do that? Pretty simple, actually. In the CodeBehind of the page, try something like this:

protected void Page_Load(object sender, EventArgs e)

{

// These values can come from anywhere, but right now, we just hardcode them

MyUserInfoBoxControl.UserName = "Jane Doe";

MyUserInfoBoxControl.UserAge = 33;

MyUserInfoBoxControl.UserCountry = "Germany";

}

Loading dynamicallySometimes you may wish to add UserControls to your page dynamically instead of declaring them. It's actually quite simple too. You need an existing control where you can add the UserControl to, for instance a Panel. If there's no logical control on your page to add it to, you may create one for the purpose - the PlaceHolder control is for situations just like that. On your page, define it like this:

<asp:PlaceHolder runat="server" ID="phUserInfoBox" />

In the CodeBehind of the page, we add the control like this:

Page 30: ASP.NET

phUserInfoBox.Controls.Add(LoadControl("~/UserInfoBoxControl.ascx"));

We use the LoadControl method to instantiate the UserControl by specifying the path. This is very easy, but also very anonymous - because we just use the LoadControl method, we can't really use our own, custom properties. To do that, we need to make .NET aware of it. On the page, add the following declaration in the top:

<%@ Reference Control="~/UserInfoBoxControl.ascx" %>

Now we can access the UserInfoBoxControl class like if it were a regular class, which also means that we can typecast the UserControl returned by the LoadControl method to this type. In the next example, we do just that, then we set the properties, and at last, we add it to the PlaceHolder:

UserInfoBoxControl userInfoBoxControl = (UserInfoBoxControl)LoadControl("~/UserInfoBoxControl.ascx");

userInfoBoxControl.UserName = "John Doe";

userInfoBoxControl.UserAge = 78;

userInfoBoxControl.UserCountry = "Spain";

phUserInfoBox.Controls.Add(userInfoBoxControl);

This will come in handy, for instance when you're adding multiple instances of the same UserControl to a single page, because you can do it inside a loop. 

Events in UserControlsIn the above section, we looked at defining properties for our UserControl, but events can be declared and used as well! This allows you to encapsulate even more functionality inside your controls, and then let your page respond to certain events, triggered by the control, if necessary.

An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. The most familiar use for events is in graphical user interfaces; typically, the classes that represent controls in the interface have events that are notified when the user does something to the control (for example, click a button).

Events, however, need not be used only for graphical interfaces. Events provide a generally useful way for objects to signal state changes that may be useful to clients of that object. Events are an important building block for creating classes that can be reused in a large number of different programs.

Events are declared using delegates. If you have not yet studied the Delegates Tutorial, you should do so before continuing. Recall that a delegate object encapsulates a method so that it can be called anonymously. An event is a way for a class to allow

Page 31: ASP.NET

clients to give it delegates to methods that should be called when the event occurs. When the event occurs, the delegate(s) given to it by its clients are invoked.

For this chapter, we will create a new and very simple UserControl, to illustrate how to create events. It won't have a real life purpose, but is only meant to show you how to use events in a UserControl.

First, we create a new, simple EventUserControl, with this code in it:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="EventUserControl.ascx.cs" Inherits="EventUserControl" %>

Page title:

<asp:TextBox runat="server" ID="txtPageTitle" />

<asp:Button runat="server" ID="btnUpdatePageTitle" OnClick="btnUpdatePageTitle_Click" Text="Update" />

All just text and server controls that we know. In the CodeBehind, it looks a bit like this:

public partial class EventUserControl : System.Web.UI.UserControl

{

private string pageTitle;

public event EventHandler PageTitleUpdated;

protected void btnUpdatePageTitle_Click(object sender, EventArgs e)

{

this.pageTitle = txtPageTitle.Text;

if(PageTitleUpdated != null)

PageTitleUpdated(this, EventArgs.Empty);

}

public string PageTitle

{

get { return pageTitle; }

Page 32: ASP.NET

}

}

We have defined a pageTitle container variable and a property for it. Then we have a new thing, an event. As you can see, it's defined much like any other kind of field, but it is a bit different. The theory about is explained in the C# tutorial, so we won't get into that here. In the Click event of our button, we set the pageTitle field. Then we check if PageTitleUpdated, our event, is null. If it's not, it means that we have subscribed to this event somewhere, and in that case, we send a notification by calling the PageTitleUpdated as a method. As parameters, we send this (a reference to the UserControl it self) as the sender, and an empty EventArgs parameter. This will make sure that all subscribers are notified that the pageTitle has just been updated. Now, in our page, I've declared our UserControl like this:

<%@ Register TagPrefix="My" TagName="EventUserControl" Src="~/EventUserControl.ascx" %>

And inserted it like this:

<My:EventUserControl runat="server" ID="MyEventUserControl" OnPageTitleUpdated="MyEventUserControl_PageTitleUpdated" />

As you can see, we have defined an event handler for the PageTitleUpdated event like if it was any other server control. In the CodeBehind of our page, we define the simple event handler for the UserControl event like this:

protected void MyEventUserControl_PageTitleUpdated(object sender, EventArgs e)

{

this.Title = MyEventUserControl.PageTitle;

}

It's that simple! Now obviously, updating the page title could have been done directly from our UserControl, so it's just to provide a simple example on how to use events, but as you will likely learn later on, this technic will come in handy in lots of situations. 

Validation

IntroductionEver since the first dynamic website was created, form validation has been an important subject. Getting user input through the system requires much attention, and with previous serverside scripting languages, there were no standard way of dealing with form validation. For that reason, clientside scripting has been used in many cases, but as you probably know, clientside scripting is not bulletproof - it can easily be bypassed

Page 33: ASP.NET

or simply turned off. With ASP.NET, webdevelopers were finally given a good, standard set of tools for validating forms. The validation controls of ASP.NET is based on both clientside and serverside technology, which brings the best from both worlds, to make sure that validating a form is as easy as ever. 

RequiredFieldValidatorThe RequiredFieldValidator is actually very simple, and yet very useful. You can use it to make sure that the user has entered something in a TextBox control. Let's give it a try, and add a RequiredFieldValidator to our page. We will also add a TextBox to validate, as well as a button to submit the form with.

<form id="form1" runat="server">

Your name:<br />

<asp:TextBox runat="server" id="txtName" />

<asp:RequiredFieldValidator runat="server" id="reqName" controltovalidate="txtName" errormessage="Please enter your name!" />

<br /><br />

<asp:Button runat="server" id="btnSubmitForm" text="Ok" />

</form>

Actually, that's all we need to test the most basic part of the RequiredFieldValidator. I'm sure that all the attributes of the controls makes sense by now, so I won't go into details about them. Try running the website and click the button. You should see something like this: 

 

If your browser supports DHTML, which most modern browers do, then you will notice that the page is not being posted back to the server - the validation is performed clientside! This is one of the really cool things about ASP.NET validators. Validation is only performed serverside if necessary! To see how it feels, you can add enableclientscript="false" to the RequiredFieldValidator and try again. Now you will see the browser posting back to the server, but the result will be the same - the validator still works! 

Right now, the button does nothing, besides posting back if the page is valid. We will change this by adding an onclick event to it:

Page 34: ASP.NET

<asp:Button runat="server" id="btnSubmitForm" text="Ok" onclick="btnSubmitForm_Click" />

In the CodeBehind file, we add the following event handler:

protected void btnSubmitForm_Click(object sender, EventArgs e)

{

if(Page.IsValid)

{

btnSubmitForm.Text = "My form is valid!";

}

}

As you will notice, we check whether or not the page is valid, before we do anything. This is very important, since this code WILL be reached if the clientside validation is not used, for some reason. Once it comes to serverside validation, it's your job to make sure that no sensitive code is executed unless you want it to. As you see, it's very simple - just check the Page.IsValid parameter, and you're good to go. Try to run the website again, and notice how the text of the button is changed if you submit a valid form. 

CompareValidatorThe CompareValidator might not be the most commonly used validator of the bunch, but it's still useful in some cases. It can compare two values, for instance the values of two controls. In the next example, I will show you a small example of how it can be used.

Small number:<br />

<asp:TextBox runat="server" id="txtSmallNumber" /><br /><br />

Big number:<br />

<asp:TextBox runat="server" id="txtBigNumber" /><br />

<asp:CompareValidator runat="server" id="cmpNumbers" controltovalidate="txtSmallNumber" controltocompare="txtBigNumber" operator="LessThan" type="Integer" errormessage="The first number should be smaller than the second number!" /><br />

As you see, we only use one validator to validate the two fields. It might seem a bit overwhelming, but it's actually quite simple. Like with the RequiredFieldValidator, we use the controltovalidate attribute to specify which control to validate. In addition to

Page 35: ASP.NET

that, we specify a control to compare. The operator attribute specifies which method to use when comparing. In this case, we use the LessThan operator, because we wish for the first control to have the smallest value. We set the type to integer, because we want to compare integers. Dates, strings and other value types can be compared as well. 

Now, try running the website, and test the two new fields. Here is what happens if you don't fill out the form correctly: 

 

If you switch the numbers, you will see another cool thing about the ASP.NET validators and clientside scripting: Validation is also performed upon exiting the fields. If you don't want this, you can turn off clientside scripting with the enableclientscript attribute. You can also compare a field to a static value. To do this, remove the controltocompare attribute, and add the valuetocompare attribute. 

However, as you may have noticed, the content of the two textboxes is not checked before comparing it. For instance, it would be possible to enter nothing, or enter a piece of text instead of a number. You should always consider this when using the CompareValidator. You can protect against empty fields with the RequiredFieldValidator, and you can protect against wrong values like text with for instance a RegularExpressionValidator, which we will show you how to use a bit later. 

If the clientside validation is not working, the invalid form will be catched by our piece of code in the CodeBehind file, as shown with the RequiredFieldValidator. This is important. 

RangeValidatorThe RangeValidator does exactly what the name implies; it makes sure that the user input is within a specified range. You can use it to validate both numbers, strings and dates, which can make it useful in a bunch of cases. Since we validated numbers the last time, we will try with a date this time.

Date:<br />

<asp:TextBox runat="server" id="txtDate" />

Page 36: ASP.NET

<asp:RangeValidator runat="server" id="rngDate" controltovalidate="txtDate" type="Date" minimumvalue="01-01-2006" maximumvalue="31-12-2006" errormessage="Please enter a valid date within 2006!" />

<br /><br />

The date format might seem a bit weird to you if you're not from Europe, where we use dd-mm-yy. You can just change it if it doesn't fit the date format on the machine you're working on. Now, try running the website, and enter a date in our new TextBox. It's only valid if the date is within 2006, and a cool sideeffect is that the date is also checked for validity. Have a look at this screenshot, which shows us that the validator reacts to an impossible date as well: 

 

And once again, if the clientside validation is not working, it will be catched in our CodeBehind, as shown with the RequiredFieldValidator.

RegularExpressionValidatorThe RegularExpressionValidator is a bit more difficult to write about, because it requires knowledge of Regular Expressions to really use it. However, RegularExpressionValidator is one of the most useful validators, because it can be used to check the validity of any kind of string. If you don't feel like learning Regular Expressions, but still feel like using this validator, have a look around the Internet. You can find many pre-made expressions out there, which can be very useful to you. Here is an example where we require a 4 digit number - nothing else is acceptable:

4 digit number:<br />

<asp:TextBox runat="server" id="txtNumber" />

<asp:RegularExpressionValidator runat="server" id="rexNumber" controltovalidate="txtNumber" validationexpression="^[0-9]{4}$" errormessage="Please enter a 4 digit number!" />

<br /><br />

The only new attribute we use, is the validationexpression. This attribute simply holds the Regular Expression which should be used to validate the field. Regular Expression simply tells the validator that a value of 4 digitgs is acceptable, and nothing else. You can use the RegularExpressionValidator for almost everything, for instance validating an e-mail or an URL. 

Page 37: ASP.NET

Try switching to Design view and select the RegularExpressionValidator on your page. Now have a look in the Properties tab of VWD. The ValidationExpression attribute has a button next to it, and if you click it, you will gain access to some default expressions, delivered by the ASP.NET team, for various purposes. Just select one of them, to use in your validator. 

CustomValidatorIf none of the other validators can help you, the CustomValidator usually can. It doesn't come with a predefined way of working; you write the code for validating your self. This is of course very powerful, since the possibilities are basically endless. A common way of using the CustomValidator is when you need to make a database lookup to see if the value is valid. The control allows you to validate both clientside and serverside, where the serverside approach is probably the most powerful. Of course, doing serverside validation requires a postback to validate, but in most cases, that's not really a problem. 

In this example, we will simply check the length of the string in the TextBox. This is a very basic and that useful example, only made to show you how you may use the CustomValidator.

Custom text:<br />

<asp:TextBox runat="server" id="txtCustom" />

<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" />

<br /><br />

As you can see, it's pretty simple. The only unknown property is the onservervalidate event. It's used to reference a method from CodeBehind which will handle the validation. Switch to our CodeBehind file and add the following method:

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)

{

if(e.Value.Length == 8)

e.IsValid = true;

else

e.IsValid = false;

}

Page 38: ASP.NET

This is very simple. The validator basically works by setting the e.IsValid boolean value to either true or false. Here we check the e.Value, which is the string of the control being validated, for it's length. If it's exactly 8 characters long, we return true, otherwise we return false. 

Although the serverside approach is probably the most powerful, you need to consider your site hosting, especially if your database receives plenty of queries. 

More validationThe validators all share a couple of attributes, which can be very useful in some cases.

ValidationGroupThis attribute was introduced with ASP.NET 2.0, and makes it possible to divide your form elements into groups. Usually, a validator control is always triggered on a postback, which could sometimes lead to problems. For instance, if you have a contact form and a search field on the same page, the validation of the contact form could be triggered by the Search button, preventing the user from searching before filling out the contact form. You can assign a name in the validationgroup property, for both the validators and the button(s) that you wish to be able to trigger the validation. The value of the attribute can be a number or a name, like validationgroup="contact_form".

SetFocusOnError (true|false)This attribute was also introduced with ASP.NET 2.0, and it does exactly what the name implies. Set SetFocusOnError to true on one or several of your validators, to give focus to the first invalid field when the form is validated.

Display (Dynamic|None|Static)This attribute decides how the validator is rendered to your page. The default value is Static, which makes the validator take up the required place whether it's visible (active) or not. You can test this by placing a piece of text directly behind a validator and load the page. If you have not set the Display attribute, or if you have set it to Static, you will see that the text is moved. However, if you set it to Dynamic, the validator will only take up any space if the validation fails and the validator is activated. This can be convenient in some cases, where you need the space the validator can take up otherwise. If you set it to None, the error message will never be shown. 

Caching

IntroductionOne of the really cool features of ASP.NET is the caching. With other technologies, caching usually requires some extra software or at least complicated code, but with ASP.NET, it's easier than ever before. You can use two different kinds of caching - output caching and standard caching. The first one is the easiest, so let's start with that. In the following chapters we will use various forms of the OutputCache directive, as well as the ASP.NET Cache object. Read on.

Page 39: ASP.NET

OutputCacheIn this chapter, we will take a look at the OutputCache directive, which is by far the easiest way of caching content with ASP.NET. As you will see in our example, it doesn’t even require any code – only some minor changes to the markup of the page, and you’re good to go. In the next chapter, we will look into more ways of using the OuputCache directive.

Here is a very simple example of a page which will show us the difference between a cached page and a non-cached page. Try creating a new project, and change the Default.aspx page to contain the following markup:

<%@ 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>Caching</title></head><body> <form id="form1" runat="server"> <%= DateTime.Now.ToString() %> </form></body></html>This is all standard stuff, except the line with the DateTime. It simply outputs the current date and time to the page. Try running the project and reload the page a couple of times. As you will see, the time is refreshed on each reload. Now, add the following line as line number 2 to our example:

<%@ OutputCache duration="10" varybyparam="None" %>

Run our project again, and reload the page a number of times. As you will see, the time is only refreshed every 10 seconds. Adding caching to your page is as simple as that! Now, the duration parameter is pretty obvious - it tells the page how many seconds to cache the content. Each time the page is requested, ASP.NET checks if the page is in the cache, and if it is, whether or not it has expired. It's served from the cache if it isn't expired - if it is, the page is removed from the cache and the page is generated from scratch and then placed in the cache.

The varybyparam is a required parameter of the OutputCache directive. It specifies a list of parameters which the cache should be varied by. For instance, if you set it to "p", the cache is now depending on the value of the parameter p. Try changing our example to something like this: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><%@ OutputCache duration="10" varybyparam="p" %><!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>Caching</title></head><body> <form id="form1" runat="server"> <%= DateTime.Now.ToString() %><br />

Page 40: ASP.NET

<a href="?p=1">1</a><br /> <a href="?p=2">2</a><br /> <a href="?p=3">3</a><br /> </form></body></html>

Now, run our example again, and try clicking the links. They each now have their own timestamp, based on when you first accessed the page. The cache is depending on the value of the p parameter! You can specify multiple parameters by seperating them with a semicolon.

OutputCache - more examplesIn the last chapter, we looked at using the OutputCache directive to cache our page very simply. In this chapter, we will look into other ways of using the OutputCache. We used varybyparam in the previous example, but you can vary your cache by other factors as well. Here is a brief list and some examples.

OutputCache - varybyparam

Please see the previous chapter for more information on the varybyparam parameter.

OutputCache - varybycontrol

The varybycontrol does exactly what it says - it varies the cache depending on the value of the specified control. For instance, you can have a dropdownlist with a set of selections, and base the content of the page based on the selected item. In that case, it will make sense to vary by the value of this control, since the content of the page changes according to it. Here is an example of using the varybycontrol parameter: <%@ OutputCache duration="10" varybyparam="none" varybycontrol="NameOfControl" %>

OutputCache - varybycustom

This is probably the least easy way of using the OutputCache system, but on the other hand, probably the most flexible. It allows you to handle the variations your self, by setting a custom string, which ASP.NET will vary the output by. To test this, you need to add a global.asax file to your project, if you don't already have one. Right click on your project in the Solution Explorer, and select Add new item. Now select the "Global Application Class" and click Ok. In the Global.asax file, you need to override the GetVaryByCustomString like this: public override string GetVaryByCustomString(HttpContext context, string custom){ if(custom == "Browser") { return context.Request.Browser.Browser; } return String.Empty;}

In this case, our caching will be varied based on which browser the user accesses the page with. The markup part should be written like this:

Page 41: ASP.NET

<%@ OutputCache duration="120" varybyparam="None" varybycustom="Browser" %>

Try accessing the page from different browsers. You will see that the output now depends on which browser you use. The Browser object comes with a bunch of useful information about the client browser - for instance you could vary by whether or not the browser supports CSS, JavaScript or something else.

OutputCache - varybyheader

This one allows you to vary the content based on one or more of the headers that browser send. Here is an example: <%@ OutputCache duration="120" varybyparam="None" varybyheader="Accept-Language" %>

This will vary cache based on the Accept-Language header, which tells the server which languages the user accepts and prefers.

OutputCache - SubstitutionWith ASP.NET version 1.0 and 1.1, there was no way to control which parts of a page would be cached, and more importantly: Which parts would be generated on each request no matter what. That meant that whenever you needed just a small part of the page to refreshed on each request, the OutputCache directive could not be used. This has changed with ASP.NET 2.0, where we may use the tag to make areas exist outside the cached content. Have a look at the following example: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><%@ OutputCache duration="120" varybyparam="None" %><!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>Caching</title></head><body> <form id="form1" runat="server"> Cached datestamp:<br /> <%= DateTime.Now.ToString() %><br /><br /> Fresh datestamp:<br /> <asp:Substitution runat="server" id="UnCachedArea" methodname="GetFreshDateTime" /> </form></body></html>

The Substitution tag takes an attribute called methodname, which holds the name of a method which should return the string to output. Once the page is loaded, no matter if it's returned from the cache or freshly generated, this method will be called, and the Substitution control will be filled with the returned string. Here is the CodeBehind, where you will see our GetFreshDateTime method: using System;using System.Data;using System.Web;

Page 42: ASP.NET

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { }

protected static string GetFreshDateTime(HttpContext context) { return DateTime.Now.ToString(); }}

Since the GetFreshDateTime method needs to be called by the Substitution control, it needs to "look" a certain way - it has to take the HttpContext as a parameter, it has to return a string, and it has to be static. Now, the HttpContext allows you to access all kinds of information about the request etc. to use for returning the proper value. For now, we simply return the current datetime. Run the example, and see how the first datestamp is cached, while the second is reloaded each time. It's as simple as that!

Caching objectsWhile the OutputCache directive is easy to use and work with, it allows you only to cache the entire page, or an entire UserControl. While this is just fine for some situations, there will be times where caching an object will be much smarter. While the following example might seem a bit silly, it does show how the Cache object can be used to store for instance an ArrayList with custom objects in it. Create a new project, or use an existing page and change the CodeBehind Page_Load method to something like this (this example doesn't require you to modify the markup part): protected void Page_Load(object sender, EventArgs e){ ArrayList datestamps; if(Cache["datestamps"] == null) { datestamps = new ArrayList(); datestamps.Add(DateTime.Now); datestamps.Add(DateTime.Now); datestamps.Add(DateTime.Now);

Cache.Add("datestamps", datestamps, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 60), System.Web.Caching.CacheItemPriority.Default, null); } else datestamps = (ArrayList)Cache["datestamps"];

foreach(DateTime dt in datestamps) Response.Write(dt.ToString() + "<br />");}

Try running this example and reloading the page. 3 instances of the current date is placed in an ArrayList, and the list is then cached using the Cache object. On each page load, the Cache is checked to see if it contains our ArrayList, using a name we have provided. If it's not, the list is generated, filled and cached. If the ArrayList is already in the cache, we pull it out and cast it to

Page 43: ASP.NET

the correct type (everything is stored as object types). No matter where we get the list from, we iterate through it and output each value.

Most of it should be pretty straight forward, except for the line where we add the list to the Cache. The Add method takes a bunch of parameters, and I will try to explain all of them.

First of all, the key we wish to store our object by, in this case we simply call it "datestamps". The key is used to get the object back from the Cache.

Next parameter is the object we wish to cache, so that goes without explaining.

Next up is the CacheDependency parameter. It can be used to tell ASP.NET that the cached item depends on other items, allowing ASP.NET to invalidate the cache if one of these items changes.

The following two parameters tells ASP.NET how and when the item should expire in the cache. The first one specifies an absolute expiration, meaning that the item will expire at a certain time of day. This is usually not what you want, so we set it to NoAbsoluteExpiration. Next we can specify a sliding expiration, which means that the item will expire after a certain amount of time, based on when the item is placed in the cache. The TimeSpan class is used, and we specify that it should expire after 0 hours, 0 minutes and 60 seconds. A priority can be set for the item in the cache. This is used when ASP.NET is removing items from the cache - items with a lower priority are removed first.

The last parameter allows us to specify a callback function for the item, which will be called once the item is removed from the cache, in case you need that. We simply specify a null value.

So, as you can see, storing items by using the Cache object is really easy. Of course, we don't really earn any performance in this example, but only the imagination is the limit here. One of the most common practices are storing objects retrieved from a database in the cache, so save resources on the database machine and allow for faster loading pages.

CookiesCookies are small pieces of text, stored on the client's computer to be used only by the website setting the cookies. This allows webapplications to save information for the user, and then re-use it on each page if needed. Here is an example where we save a users choice of background color:

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

Page 44: ASP.NET

<!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>Cookies</title>

</head>

<body runat="server" id="BodyTag">

<form id="form1" runat="server">

<asp:DropDownList runat="server" id="ColorSelector" autopostback="true" onselectedindexchanged="ColorSelector_IndexChanged">

<asp:ListItem value="White" selected="True">Select color...</asp:ListItem>

<asp:ListItem value="Red">Red</asp:ListItem>

<asp:ListItem value="Green">Green</asp:ListItem>

<asp:ListItem value="Blue">Blue</asp:ListItem>

</asp:DropDownList>

</form>

</body>

</html>

The page simply contains a DropDownList control, which automatically posts back each time a new item is selected. It has 3 different colors, besides the default one, which is simply white. Once a new item is selected, the ColorSelector_IndexChanged method is fired, from our CodeBehind file:

using System;

using System.Data;

using System.Web;

public partial class _Default : System.Web.UI.Page

{

Page 45: ASP.NET

protected void Page_Load(object sender, EventArgs e)

{

if(Request.Cookies["BackgroundColor"] != null)

{

ColorSelector.SelectedValue = Request.Cookies["BackgroundColor"].Value;

BodyTag.Style["background-color"] = ColorSelector.SelectedValue;

}

}

protected void ColorSelector_IndexChanged(object sender, EventArgs e)

{

BodyTag.Style["background-color"] = ColorSelector.SelectedValue;

HttpCookie cookie = new HttpCookie("BackgroundColor");

cookie.Value = ColorSelector.SelectedValue;

cookie.Expires = DateTime.Now.AddHours(1);

Response.SetCookie(cookie);

}

}

Okay, two different parts to be explained here. First, the Page_Load method, which is called on each page request. Here we check for a cookie to tell us which background color should be used. If we find it, we set the value of our dropdown list to reflect this, as well as the background color of the page, simply by accessing the style attribute of the body tag. 

Then we have the ColorSelector_IndexChanged method, which is called each time the user selects a new color. Here we set the background color of the page, and then we create a cookie, to hold the value for us. We allow it to expire after one hour, and then we set it by calling the SetCookie method on the Response object. 

Try running the example, and set a color. Now close the browser, and start it up again. You will see that the choice of color is saved, and it will remain saved for an hour.

Page 46: ASP.NET

However, nothing prevents you from saving the choice for much longer. Simply add a bigger value to the expiry date, or set an absolute value for it. 

No sensitive information should ever be stored in a cookie.

SessionsSessions can be used to store even complex data for the user just like cookies. Actually, sessions will use cookies to store the data, unless you explicitly tell it not to. Sessions can be used easily in ASP.NET with the Session object. We will re-use the cookie example, and use sessions instead. Keep in mind though, that sessions will expire after a certain amount of minutes, as configured in the web.config file. Markup code:

<%@ 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>Sessions</title>

</head>

<body runat="server" id="BodyTag">

<form id="form1" runat="server">

<asp:DropDownList runat="server" id="ColorSelector" autopostback="true" onselectedindexchanged="ColorSelector_IndexChanged">

<asp:ListItem value="White" selected="True">Select color...</asp:ListItem>

<asp:ListItem value="Red">Red</asp:ListItem>

<asp:ListItem value="Green">Green</asp:ListItem>

<asp:ListItem value="Blue">Blue</asp:ListItem>

</asp:DropDownList>

</form>

</body>

</html>

And here is the CodeBehind:

Page 47: ASP.NET

using System;

using System.Data;

using System.Web;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if(Session["BackgroundColor"] != null)

{

ColorSelector.SelectedValue = Session["BackgroundColor"].ToString();

BodyTag.Style["background-color"] = ColorSelector.SelectedValue;

}

}

protected void ColorSelector_IndexChanged(object sender, EventArgs e)

{

BodyTag.Style["background-color"] = ColorSelector.SelectedValue;

Session["BackgroundColor"] = ColorSelector.SelectedValue;

}

}

As you can see, the example doesn't need a lot of changes to use sessions instead of cookies. Please notice that session values are tied to an instance of your browser. If you close down the browser, the saved value(s) will usually be "lost". Also, if the webserver recycles the aspnet_wp.exe process, sessions are lost, since they are saved in memory as well. This can be avoided by saving session states on a separate StateServer or by saving to a SQL server, but that's beyond the scope of this section. 

Page 48: ASP.NET

To summarize, Sessions are stored per-user in memory(or an alternative Session-State) on the server. Sessions use a cookie(session key) to tie the user to the session. This means no "sensitive" data is stored in the cookie on the users machine.

Sessions are generally used to maintain state when you navigate through a website. However, they can also be used to hold commonly accessed objects. Only if the Session-state is set to InProc, if set to another Session-State mode the object must also serializable.

Session["userName"] = "EvilBoy";

if(Session["userName"] != null)  lblUserName.Text = Session["userName"].ToString();

Configuring Session State

ASP.NET gives you several choices for managing session state. You can turn it off

completely, you may run session state in the ASP.NET worker process, you may run it

on a separate state server, or you may run it from a SQL Server database. Here's a

rundown of the options available:

Don't use it at all.

By disabling session state, your application performance will increase because

the page doesn't need to load the session when starting, nor does it need to

store session state when it's going away. On the other hand, you won't be able to

associate any data with a particular user.

Store session state in proc.

This is how session state is handled by default. In this case, the session

dictionaries (the Sessionobjects) are managed in the same process as the page

and handler code. The advantage of using session state in process is that it's

very fast and convenient. However, it's not durable. For example, if you restart

IIS or somehow knock the server down, all session state is lost. In some cases,

this may not be a big deal. However, if your shopping cart represents a shopping

cart containing sizeable orders, losing that might be a big deal. In addition, the in

process Session manager is confined to a single machine, meaning you can't use

it in a Web farm.

Page 49: ASP.NET

Store session state in a state server.

This option tells the ASP.NET runtime to direct all session management activities

to a separate process running on a particular machine. This option gives you the

advantage of running your server in a Web farm. A Web farm is a group of

servers tied together to serve Web pages. The ASP.NET Session State facilities

support Web farms explicitly. To run in a Web farm, you would direct all your

applications to go to the same place to retrieve session information. The

downside to this approach is that it does impede performance somewhat-

applications need to make a network round-trip to the state server when loading

or saving session information.

Store session state in a database.

Configuring your application to use a SQL Server database for state management

causes ASP.NET to store session information within a SQL Server database

somewhere on your network. Use this option when you want to run your server

from within a Web farm when you want session state to be durable and safe.

There are two ways to configure ASP.NET: the hard way and the easy way. As with most

other configuration settings, the ASP.NET session state configuration ultimately happens

within the Web.Config file. As always, you may configure Web.Config the hard way by

using the typing Wizard (that is, typing the settings in by hand). Alternatively, you may

use the ASP.NET Configuration Settings dialog box from IIS.

Page 50: ASP.NET

Turning Off Session State

The ASP.NET session state configuration tool available through IIS will touch your Web

site's Web.Config file and insert the right configuration strings to enforce the settings

you choose. To turn off session state completely, select Off from the session state mode

control.

Storing Session State InProc

To store session state in the ASP.NET worker process, select InProc from the session

state mode control. Your application will retrieve and store session information very

quickly, but it will be available only to your application (and not on a Web form).

Page 51: ASP.NET

Storing Session State in a State Server

To have ASP.NET store session state on another server on your network,

select StateServer from theSessionState mode control. When you select this item, the

dialog box will enable the Connection String text box and the network timeout text box.

Insert the protocol, IP address, and port for the state server in the Connection String

text box. For example, the string:

tcpip=127.0.0.1:42424

will store the session state on the local machine over port 42424. If you want to store

the session state on a machine other than your local server, change the IP address.

Before session state is stored on a machine, you need to make sure the ASP.NET state

server is running on that machine. You may get to it via the Services panel under the

control panel.

Page 52: ASP.NET

Storing Session State in a Database

The final option for storing session state is to use a SQL Server database.

Select SQLServer from the ASP.NET session state mode combo box. You'll be asked to

enter the connection string to the SQL Server state database. Here's the string they

provide by default:

data source=127.0.0.1;Integrated Security=SSPI

You may point ASP.NET so it references a database on another machine. Of course, you

need to have SQL Server installed on the target machine to make this work. In addition,

you'll find some SQL scripts to create the state databases in your .NET system directory

(C:\WINDOWS\[[<img src="images/shy.gif"/>]]Microsoft.NET\Framework\v2.0.50215 on

this machine at the time of this writing). The Aspnet_regsql.exe tool will set up the

databases for you.

ViewState

Another approach to saving data for the user, is the ViewState. As described elsewhere in this tutorial, the ViewState allows ASP.NET to repopulate form fields on each postback to the server, making sure that a form is not automatically cleared when the user hits the submit button. All this happens automatically, unless you turn it off, but you can actually use the ViewState for your own purposes as well. Please keep in mind though, that while cookies and sessions can be accessed from all your pages on your website, ViewState values are not carried between pages. Here is a simple example of using the ViewState to carry values between postbacks:

<%@ 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>ViewState</title>

</head>

<body>

<form id="form1" runat="server">

Page 53: ASP.NET

<asp:TextBox runat="server" id="NameField" />

<asp:Button runat="server" id="SubmitForm" onclick="SubmitForm_Click" text="Submit & set name" />

<asp:Button runat="server" id="RefreshPage" text="Just submit" />

<br /><br />

Name retrieved from ViewState: <asp:Label runat="server" id="NameLabel" />

</form>

</body>

</html>

And the CodeBehind:

using System;

using System.Data;

using System.Web;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if(ViewState["NameOfUser"] != null)

NameLabel.Text = ViewState["NameOfUser"].ToString();

else

NameLabel.Text = "Not set yet...";

}

protected void SubmitForm_Click(object sender, EventArgs e)

{

Page 54: ASP.NET

ViewState["NameOfUser"] = NameField.Text;

NameLabel.Text = NameField.Text;

}

}

Try running the project, enter your name in the textbox and press the first button. The name will be saved in the ViewState and set to the Label as well. No magic here at all. Now press the second button. This one does nothing at all actually, it just posts back to the server. As you will notice, the NameLabel still contains the name, but so does the textbox. The first thing is because of us, while the textbox is maintained by ASP.NET it self. Try deleting the value and pressing the second button again. You will see that the textbox is now cleared, but our name label keeps the name, because the value we saved to the ViewState is still there! 

ViewState is pretty good for storing simple values for use in the form, but if you wish to save more complex data, and keep them from page to page, you should look into using cookies or sessions, as described in the previous chapters. 

Using the Web.configWeb.config acts as a central location for storing the information to be accessed by web pages. This information could be a Connection String stored at a centralized location so that it can be accessed in a data-driven page. If the connection string changes its just a matter of changing it at one place.

If you open a new Web Application in Visual Studio, you will notice Visual Studio automatically creates a Web.config file for you. This file can be one of several Web.config files on your machine. Others can be located in the .NET framework library, server root, and even subdirectories. All parent Web.config file settings will be inherited by child Web.config files.  All child Web.config files can overwrite the settings listed in their parent Web.config files unless you specify the setting to not be overwritten.  The Web.config file in your current working directory will have the most dominate settings.

All settings are inside of <configuration> xml tags. The Web.config file is an xml file which must be declared at the top of the document. Below is an example of that.

<?xml version="1.0"?>

<configuration>     <system.web>           <!— sections-->         </system.web>      <appSettings>           <!— sections -->         </appSettings >

Page 55: ASP.NET

</configuration>

As you can see in the example above, I've included the 2 most common child nodes of the <configuration> tag. The <system.web> child and the <appSettings> child. Like their names indicate, the <system.web> tag contains elements that more server specific such as security, custom error pages, etc. The <appSettings> tag holds more of the information that can be used on actual applications such as sql connection strings.

There are 2 different types of security - Authentication and Authorization. Authentication

specifies the type of authentication used through the application such as Windows, Forms, Passport mode or None if no authentication is necessary. Authorization specifies which users can access which pages. An example of each type is listed below:

<system.web>      <authentication mode="Forms" />     <authorization>           <allow roles="Administrators" />           <deny users="*" />      </authorization> </system.web>

Another common setting to change in your Web.config file for your web site is custom error pages. Default server error pages are usually plain, basic, and aren't modeled after your template or contain possible suggestions for what page you were trying to access. By using the <customErrors> tag you can set each error to use a specific page.

An example is below:

<system.web>     <customErrors mode="RemoteOnly" defaultRedirect="error.aspx">          <error statusCode="404" redirect="pagemissing.aspx" />     </customErrors> </system.web>

Now that we've covered the most common child nodes of <system.web>, we can move on to <appSettings>.

Due to the extra security on Web.config files, important variable strings can be stored to avoid accidental exposure. It isn't uncommon for the debug variable to be set to true and errors allow unwanted eyes to see confidential information. A common example of this would be a database connection string. By using the <add> tags you can store name/value pairs to be accessed by your application.

This is an example of how to store a database connection string.

<appSettings>      <add key="connString" value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" />

Page 56: ASP.NET

</appSettings>

This is an example of the code you'd use to access the stored name/value pairs in the Web.config file.

//c#Sqlconnection Sqlconn = New SqlConnection(ConfigurationManager.AppSettings["connString"]));

//vb.netDim SqlConn as New SqlConnection(ConfigurationManager.AppSettings["connString"]))

Authentication and Authorization in ASP.NET

Authentication in ASP.NETThere are two closely interlinked concepts at the heart of security for distributed applications - authentication and authorization. Authentication is the process of obtaining some sort of credentials from the users and using those credentials to verify the user's identity. Authorization is the process of allowing an authenticated user access to resources. Authentication is always precedes to Authorization; even if your application lets anonymous users connect and use the application, it still authenticates them as being anonymous. ASP.net provides flexible set of alternatives for authentication. You can perform authentication yourself in code or delegate authentication to other authorities (such as Microsoft Passport). In fact sometimes it seems ASP.net authentication is a bit too flexible; it can be difficult for a new developer to know just where to start. In this section, we review the settings in ASP.net and Internet Information Services (IIS) that control authentication and authorization in ASP.net applications.

An ASP.net application has two separate authentication layers. That is because ASP.net is not a standalone product. Rather it is a layer on top of IIS. All requests flow through IIS before they are handed to ASP.net. As a result, IIS can decide to deny access without the ASP.net process even knowing that someone requested a particular page. Here is an overview of the steps in the joint IIS and ASP.net authentication process.

1. IIS first checks to make sure the incoming request comes from an IP address that is allowed access to the domain. If not it denies the request.

2. Next IIS performs its own user authentication if it configured to do so. By default IIS allows anonymous access, so requests are automatically authenticated, but you can change this default on a per - application basis with in IIS.

3. If the request is passed to ASP.net with an authenticated user, ASP.net checks to see whether impersonation is enabled. If impersonation is enabled, ASP.net acts as though it were the authenticated user. If not ASP.net acts with its own configured account.

4. Finally the identity from step 3 is used to request resources from the operating system. If ASP.net authentication can obtain all the necessary resources it grants the users request otherwise it is denied. Resources can include much more than just the

Page 57: ASP.NET

ASP.net page itself you can also use .Net's code access security features to extend this authorization step to disk files, Registry keys and other resources.

As you can see several security authorities interact when the user requests an ASP.net page. If things are not behaving the way you think they should, it can be helpful to review this list and make sure you have considered all the factors involved

Authentication providers

Assuming IIS passes a request to ASP.net, what happens next? The answer depends on the configuration of ASP.net itself. The ASP.net architecture includes the concept of and authentication provider a piece of code whose job is to verify credentials and decide whether a particular request should be considered authenticated. Out of the box ASP.net gives you a choice of three different authentication providers.

The windows Authentication provider lets you authenticate users based on their windows accounts. This provider uses IIS to perform the authentication and then passes the authenticated identity to your code. This is the default provided for ASP.net.

The passport authentication provider uses Microsoft's passport service to authenticate users.

The forms authentication provider uses custom HTML forms to collect authentication information and lets you use your own logic to authenticate users. The user's credentials are stored in a cookie for use during the session.

Selecting an authentication provider is as simple as making an entry in the web.config file for the application. You can use one of these entries to select the corresponding built in authentication provider:

<authentication mode="windows">authentication mode="passport"><authentication mode="forms">

ASP.net also supports custom authentication providers. This simply means that you set the authentication mode for the application to none, then write your own custom code to perform authentication. For example, you might install an ISAPI filter in IIS that compares incoming requests to list of source IP addresses, and considers requests to be authenticated if they come from an acceptable address. In that case, you would set the authentication mode to none to prevent any of the .net authentication providers from being triggered.

The fig below illustrates the authorization and authentication mechanisms provided by ASP.NET and IIS.

Page 58: ASP.NET

Windows authentication and IIS

If you select windows authentication for your ASP.NET application, you also have to configure authentication within IIS. This is because IIS provides Windows authentication. IIS gives you a choice for four different authentication methods:

Anonymous, basic, digest, and windows integrated

If you select anonymous authentication, IIS doesn't perform any authentication, Any one is allowed to access the ASP.NET application.

If you select basic authentication, users must provide a windows username and password to connect. However this information is sent over the network in clear text, which makes basic authentication very much insecure over the internet.

If you select digest authentication, users must still provide a windows user name and password to connect. However the password is hashed before it is sent across the network. Digest authentication requires that all users be running Internet Explorer 5 or later and that windows accounts to stored in active directory.

If you select windows integrated authentication, passwords never cross the network. Users must still have a username and password, but the application uses either the Kerberos or challenge/response protocols authenticate the user. Windows-integrated authentication requires that all users be running internet explorer 3.01 or later Kerberos is a network authentication protocol. It is designed to provide strong authentication for client/server applications by using secret-key cryptography. Kerberos is a solution to network security

Page 59: ASP.NET

problems. It provides the tools of authentication and strong cryptography over the network to help to secure information in systems across entire enterprise

Passport authentication

Passport authentication lets you to use Microsoft's passport service to authenticate users of your application. If your users have signed up with passport, and you configure the authentication mode of the application to the passport authentication, all authentication duties are offloaded to the passport servers.

Passport uses an encrypted cookie mechanism to indicate authenticated users. If users have already signed into passport when they visit your site, they'll be considered authenticated by ASP.NET. Otherwise they'll be redirected to the passport servers to log in. When they are successfully log in, they'll be redirected back to your site

To use passport authentication you have to download the Passport Software Development Kit (SDK) and install it on your server. The SDK can be found at http://msdn.microdoft.com/library/default.asp?url=/downloads/list/websrvpass.aps. It includes full details of implementing passport authentication in your own applications.

Forms authentication1. Forms authentication provides you with a way to handle authentication using your

own custom logic with in an ASP.NET application. The following applies if you choose forms authentication.

2. When a user requests a page for the application, ASP.NET checks for the presence of a special session cookie. If the cookie is present, ASP.NET assumes the user is authenticated and processes the request.If the cookie isn't present, ASP.NET redirects the user to a web form you provide

3. You can carry out whatever authentication, checks you like in your form. When the user is authenticated, you indicate this to ASP.NET by setting a property, which creates the special cookie to handle subsequent requests.

Configuring Authorization

After your application has authenticated users, you can proceed to authorize their access to resources. But there is a question to answer first: Just who is the user to whom your are granting access? It turns out that there are different answers to that question, depending on whether you implement impersonation. Impersonation is a technique that allows the ASP.NET process to act as the authenticated user, or as an arbitrary specified user

ASP.NET impersonation is controlled by entries in the applications web.config file. The default setting is "no impersonation". You can explicitly specify that ASP.NET shouldn't use impersonation by including the following code in the file

<identity impersonate="false"/>

With this setting ASP.NET does not perform impersonation. It means that ASP.NET will run with its own privileges. By default ASP.NET runs as an unprivileged account named ASPNET. You can change this by making a setting in the processModel section of the machine.config file. When you make this setting, it automatically applies to every site on the server. To use a high-privileged system account instead of a low-privileged, set the userName attribute of the processModel element to SYSTEM. Using this setting is a definite security risk, as it

Page 60: ASP.NET

elevates the privileges of the ASP.NET process to a point where it can do bad things to the operating system.

When you disable impersonation, all the request will run in the context of the account running ASP.NET: either the ASPNET account or the system account. This is true when you are using anonymous access or authenticating users in some fashion. After the user has been authenticated, ASP.NET uses it own identity to request access to resources.

The second possible setting is to turn on impersonation.

<identity impersonate="true"/>

In this case, ASP.NET takes on the identity IIS passes to it. If you are allowing anonymous access in IIS, this means ASP.NET will impersonate the IUSR_ComputerName account that IIS itself uses. If you aren't allowing anonymous access,ASP.NET will take on the credentials of the authenticated user and make requests for resources as if it were that user. Thus by turning impersonation on and using a non-anonymous method of authentication in IIS, you can let users log on and use their identities within your ASP.NET application.

Finally, you can specify a particular identity to use for all authenticated requests

<identity impersonate="true" username="DOMAIN\username" password="password"/>

With this setting, all the requests are made as the specified user (Assuming the password it correct in the configuration file). So, for example you could designate a user for a single application, and use that user's identity every time someone authenticates to the application. The drawback to this technique is that you must embed the user's password in the web.config file in plain text. Although ASP.NET won't allow anyone to download this file, this is still a security risk if anyone can get the file by other means.

Best practices

Now that you know what the choices are for ASP.NET authentication, here are some points that tell which to choose.

If there is nothing sensitive about the application, stick with no authentication in ASP.NET and anonymous authentication in IIS. That lets anyone who can reach the host computer use the application.

If you have to authenticate users, there are several choices. If all users have accounts on your network, use Windows authentication in ASP.net with one of the strong IIS authentication settings. If users don't have network accounts, own custom authentication scheme is preferred, means forms authorization.

If different users must have different privileges, impersonation in ASP.net configuration files needs to be turn on.

Page 61: ASP.NET

Master Pages

Uses of Master Pages

The master pages can be used to accomplish the following:

Creating a set of controls that are common across all the web pages and attaching them to all the web pages.

A centralized way to change the above created set of controls which will effectively change all the web pages.

Dynamically changing the common UI elements on master page from content pages based on user preferences.

Terminology

Let us look at the basic terminology that needs to be understood before jumping into master pages:

Masterpage: Gives us a way to create common set of UI elements that are required on multiple pages of our website.

ContentPage: The ASP.NET web page that will use master page to have the common UI elements displayed on rendering itself.

ContentPlaceHolder: A control that should be added on the MasterPage which will reserve the area for the content pages to render their contents.

ContentControl: A control which will be added on content pages to tell these pages that the contents inside this control will be rendered where the MasterPage's ContentPlaceHolder is located.

Creating a MasterPage

To create a master page, we need to:

1. Go to "Add New Item".2. Select the MasterPage.

Page 62: ASP.NET

3. Let's say our master page is MasterPageOne.Master.4. We will now add a menu bar on this master page on top of the page. This Menu bar

will be common to all the pages (since it is in Masterpage).

5. Once we have menubar added, we can have content pages use the master page.

6. Let's add few content pages like default.aspx, about.aspx, Contact.aspx. (We are simply creating some dummy pages with no functionality as we want to see the masterpage working, but these content pages can have any level of complex logic in them).

7. When we add these content pages, we need to remember to select the option of "Use master Page".

Page 63: ASP.NET

and select the master page.

Now let's look at the stuff that is important. When we look at the MasterPage, we will see that masterpage has aContentPlaceHolder control. All the code that is common for the content pages is outside theContentPlaceHolder control (in our case, a simple menubar).

 Collapse | Copy Code

<div align="center"> <h1>My Test WebSite</h1> <asp:Menu ID="Menu1" runat="server" BackColor="#B5C7DE" DynamicHorizontalOffset="2"

Page 64: ASP.NET

Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284E98" Orientation="Horizontal" StaticSubMenuIndent="10px"> <StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" /> <DynamicHoverStyle BackColor="#284E98" ForeColor="White" /> <DynamicMenuStyle BackColor="#B5C7DE" /> <StaticSelectedStyle BackColor="#507CD1" /> <DynamicSelectedStyle BackColor="#507CD1" /> <DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" /> <Items> <asp:MenuItem Text="HOME" Value="HOME" NavigateUrl="~/Default.aspx"> </asp:MenuItem> <asp:MenuItem Text="ABOUT" Value="ABOUT" NavigateUrl="~/about.aspx"> </asp:MenuItem> <asp:MenuItem Text="CONTACT" Value="CONTACT" NavigateUrl="~/contact.aspx"> </asp:MenuItem> </Items> <StaticHoverStyle BackColor="#284E98" ForeColor="White" /> </asp:Menu>

<!-- Here we have content place holder where all content pages will render their controls --> <asp:contentplaceholder id="ContentPlaceHolder1" runat="server"> </asp:contentplaceholder>

</div>

Adding the ContentPages

If we look at our content pages, we will find a simple Content control added to each content page. This is the area where we will be adding our controls to be rendered along with the master page. (In our case, just simple strings.)

 Collapse | Copy Code

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"><h2>This is a the CONTACT page.</h2></asp:Content>

Once we have all the master pages and content pages ready, we can test run our website.

Page 65: ASP.NET

So the common set of controls and behavior has now been added to all the content pages. We can have any number of controls and functionality on the master pages.

Changing the Master Page's Properties from Content Pages

There are times when we need to change some properties of master pages based on the current content page. These properties could be related to visible aspects of master page like UI elements or they could be of behavior aspects. The best way to do that is to have public properties in master pages that the individual content pages can use to customize the look/behavior of master page for that particular master page.

Let us, in our small test website, have a label in master page that will tell the user about the current page. Let's think of this label as breadcrumbs (just to illustrate there is no way, breadcrumbs should be created like this).

This label will display the string that is set by the Content page so we need to have a public property in the master page to accomplish that.

 Collapse | Copy Code

public string PageName

Page 66: ASP.NET

{ get { return lblpageName.Text; } set { lblpageName.Text = value; }}

Now we can use this property to set the PageName property of master page from content pages.

One important thing to mention here is that if we want to use this property from our content page, then we need to have a @Mastertype declaration in our content pages. This declaration will enable the content pages to use thepublic properties of Master Pages.

 Collapse | Copy Code

<%@ MasterType VirtualPath="~/MasterPageOne.master" %>

and from our content pages, we can simply set the property of the master page.

 Collapse | Copy Code

//default.aspxprotected void Page_Load(object sender, EventArgs e){ this.Master.PageName = "/Default.aspx";}

//about.aspxprotected void Page_Load(object sender, EventArgs e){ this.Master.PageName = "/About.aspx";}

//contact.aspxprotected void Page_Load(object sender, EventArgs e){ this.Master.PageName = "/Contact.aspx";}

and now if we run the website, we can see the label on master page showing the appropriate page name which is being set by the content page.

Page 67: ASP.NET

Changing the Master Page Dynamically

Now there are scenarios when we want the user to change the layout of the website. Since our website's layout is defined by the masterpage, to accomplish this we need the ability to change the master pages dynamically from the code.

So to do this, let us add one more master page to the website. This master page will have the menu vertically aligned on the left side unlike the first which has it on top.

Page 68: ASP.NET

Now to let the user change the MasterPage:

We need to have the option of changing the master page - let's have a new page change.aspx, we will place radio button on this page to be able to change master page for this page.

We need to save the current selected master page - let's save it in a session variable.

Change the master page on the fly - We need to do it in Page_PreInit of content Page Change.aspx.

 Collapse | Copy Code

//global.asaxvoid Session_Start(object sender, EventArgs e){ // Code that runs when a new session is started Session["master"] = "~/MasterPageOne.master";}

//change.aspxprotected void Page_Load(object sender, EventArgs e){ if (IsPostBack == false) { RadioButtonList1.SelectedValue = Session["master"].ToString(); }}protected void Button1_Click(object sender, EventArgs e){ Session["master"] = RadioButtonList1.SelectedValue; //lets reload to see the change Response.Redirect("Change.aspx");}

protected void Page_PreInit(object sender, EventArgs e){ this.MasterPageFile = Session["master"].ToString();}

Page 69: ASP.NET

Now when the user changes the Master Page from change.aspx, the masterpage for that page will be changed for that page for that session.

Now let us try to sum up what we have seen so far by doing this small unrealistic example.

MasterPage gives a mechanism to create Consistent web pages. We need to have ContentPlaceholder on each MasterPage and a Content control

on each Contentpage.

Content pages can change the master page visibility and behavior by using the public property provided byMasterPage.

The MasterPage can be changed on the fly (programmatically) too.

There is also a possibility of having nested master pages if we carefully use MasterPage inside theContentPlaceHolder of another master page thus exposing a new ContentPlaceHolder of nestedMasterPage for content pages to use.

Custom Server Control

A Server Control is something like a textbox or label that either gathers data or displays dataserver side.

The basic setup of a Server control looks like this:

<asp:DropDownList ID="DropDownList1" runat="server" />

lets break down that tag

<asp: this part is the tag prefix that was defined in your register tag. It points to a certain assembly, and namespace.

:DropDownList this part defines the Control itself. Later i will show you where this comes from.

Page 70: ASP.NET

ID="DropDownList1" this defines the identity of this instance of the control. It will be used throughout your code to define this instance.

runat="server" this tells the aspx page that the control that is being rendered is handled by serverside code.

/> closes the tag. Just like in HTML all your asp items need a closing tag.

ok now that we know the basic layout of an asp control tag, how are we going to create our own?

Well to do this Simply open up Visual Studio 2010 >> File >> new Project >> other languages >> visual c#(you can do this in VB aswell, but for this tutorial i'll be using C#) >> Windows >> Web Control Library.

after selecting Web Control Library you will want to give it a good descriptive name. For this tutorial lets call it YearDropDownList.

after you click ok you will see a .cs file open called WebCustomControl1.cs in that file it contains the basic setup for creating a custom control:

using System;using System.Collections.Generic;using System.Linq;using System.Collections.Generic;using System.ComponentModel;using System.Text;using System.Web;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;

namespace OnlinePortal{ [DefaultProperty("Text")] [ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")] public class WebCustomControl1 : WebControl { [Bindable(true)] [Category("Appearance")] [DefaultValue("")] [Localizable(true)] public string Text { get { String s = (String)ViewState["Text"]; return ((s == null) ? String.Empty : s); }

Page 71: ASP.NET

set { ViewState["Text"] = value; } }

protected override void RenderContents(HtmlTextWriter output) { output.Write(Text); } }

}

notice this part

1[ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]

this is whats going to define the control in the toolbox. Lets go ahead and change that to say YearDropDownList

1 [ToolboxData("<{0}:YearDropDownList runat=server></{0}:YearDropDownList>")]

while we are at it lets change the name of the .cs file to YearDropDownList.cs

you will also notice that this class extends WebControl. WebControl is the base class that houses all the properties for a control. I.E height, width, fonts, etc.

for this tutorial we will go ahead and extend of a already defined control DropDownList. So change the line

1 public class WebCustomControl1 : WebControl

to read

1 public class WebCustomControl1 : DropDownList

Page 72: ASP.NET

below that you see a group of declarations:

1 [Bindable(true)]

2         [Category("Appearance")]

3         [DefaultValue("")]

4         [Localizable(true)]

these tell about the program. 

Bindable: specifies for visual designers whether it is meaningful to bind the property to data

Category: specifies how to categorize the property in the visual designer's property browser

DefaultValue: specifies a default value for the property

Localizable: specified as true or false, specifies for visual designers whether it is meaningful to localize the property.

(definitions obtains from : http://msdn.microsof...y/yhzc935f.aspx )

one that isnt shown here is Description. Description Allows you to set a description that will be shown at the bottom of the properties windowwhen a user selects that property.

next we have 

01 public string Text

02         {

03             Get

04             {

Page 73: ASP.NET

05                 String s = (String)ViewState["Text"];

06                 return ((s == null) ? String.Empty : s);

07             }

08

09             Set

10             {

11                 ViewState["Text"] = value;

12             }

13         }

14        

The above code is called a property. Properties define the look and feel of a server control. You can create any property you want as long as you apply it to your rendered control properly. The text property will not be needed so go ahead and remove that.instead lets go ahead and enter a property in called startyear.

01 //define the get and set methods for storing and retrieving the start year

02        

03        protected int _StartYear;

04        public int StartYear

05        {

06            Get

07            {

08                return _StartYear;

09            }

Page 74: ASP.NET

10            Set

11            {

12               _StartYear = value;//Setting startyear to value allows the user to input an int value and store it in startyear.

13            }

14        }

15       

after we get done defining the start year lets go ahead and define a property for the endyear

01 protected int _EndYear;

02  public int EndYear

03  {

04      get

05      {

06          return _EndYear;

07      }

08      set

09      {

10          _EndYear = value;

11      }

12 }

now we have defined two properties, start year and end year. What to do now. Well thats relativly simple. We want to populate the dropdownlist will all years between _StartYear and _EndYear to do this we create a method called

Page 75: ASP.NET

PopulateDropDown()

01 private void populatedropdown()

02 {

03     //notice we use the property names instead of the variable names.

04     for (int i = this.StartYear; i <= this.EndYear; i++)

05     {

06         //adds the specified year              

07         this.Items.Add(new ListItem(i.ToString(), i.ToString()));

08

09     }

10 }

So if the startyear was set to 2005 and the endyear was set to 2010 it would add all the years starting at 2005 and going through 2010. 

next we need to call populatedropdown() from somewhere. We will go ahead and do this in the OnPreRender method.

1//notice that the OnPrePrender method already exsists so we will be overriding it

2  protected override void OnPreRender(EventArgs e)

3         {

4             base.OnPreRender(e);

5             populatedropdown();

6         }

Page 76: ASP.NET

Now we have that done. Lets go ahead and remove the RenderContents method. We dont use that so lets not keep it in the program.

ok, We are done building the actual control now lets move on to how to impliment it. 

Go ahead and click on Solution 'YearDropDownList' then go file >> add >> new Project >> other languages >> visual c# >> Web >> ASP.Net Web Application. 

Lets name this one YearDropDownListTest.

ok once that loads up right click on the Project YearDropDownListTest and select Set as Startup Project. 

next right click on References and select Add Reference. Once that window pops up select projects, click on YearDropDownList and click ok. 

this adds the reference to the custom control you created. Now we'll go ahead and add a register tag in our default so we can use it. 

double click the Default.asp page, if it doesnt take you straight to source view, go to sourceview.

At the top where you see 

1

<%@ Page

Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"Inherits="YearDropDownListTest._Default" %>

create a blank space under it and enter 

1<%@ Register

Assembly="YearDropDownList" Namespace="YearDropDownList"TagPrefix="CDDL" %>

this will register the custom control. 

Now go ahead back to Design view and check your toolbox. Notice that your control is

Page 77: ASP.NET

there? Now drag and drop it to the page and use it likea normal control

Themes and Skins in ASP.NETWhen you build a Web application, it usually has a similar look and feel across all its pages. Not too many

applications are designed with each page dramatically different from the next. Generally, for your

applications you use similar fonts, colors, and server control styles across all the pages.

You can apply these common styles individually to each and every server control or object on each page,

or you can use a new capability provided by ASP.NET 2.0 to centrally specify these styles. All pages or

parts of pages in the application can then access them.

Themes are the text-based style definitions in ASP.NET 2.0 that are the focus of this chapter.

Using ASP.NET 2.0 Packaged ThemesIn case of CSS you can define only style properties but a theme can define multiple properties of a control not just style properties such as you can specify the graphics property for a control, template layout of a GridView control etc. You can apply multiple style sheets to a single page but you cannot apply multiple themes to a single page. Only one theme you can apply for a single page.

You can apply ASP.NET themes at the application, page, or server control level.

To make life easy for the developer, ASP.NET comes with free prepackaged themes that you can use for

your pages or applications. You find these themes located at C:\WINDOWS \Microsoft .NET \

Framework \v2.0.xxxxx \ASP.NETClientFiles \Themes. The available themes that come with

ASP.NET 2.0 include

BasicBlue

SmokeAndGlass

Applying a theme to a single ASP.NET page

In order to see how to use one of these themes, create a basic page, which includes text, a text box, a

button, and a calendar. This is shown in Listing 7-1.

Listing 7-1: An ASP.NET page that does not use themes

1. <%@Page Language="VB" %>

2. <html xmlns="http://www.w3.org/1999/xhtml" >

3. <head runat="server">

4. <title>INETA</title>

5. </head>

6. <body>

7. <form id="form1" runat="server">

8. <h1>International .NET Association (INETA)</h1><br />

9. <asp:Textbox ID="TextBox1" Runat="server" /><br />

10. <br />

Page 78: ASP.NET

11. <asp:Calendar ID="Calendar1" Runat="server" /><br />

12. <asp:Button ID="Button1" Runat="server" Text="Button" />

13. </form>

14. </body>

15. </html>

This simple page shows some default server controls that appear just as you would expect, but that you

can change with one of the ASP.NET built-in themes. When the page is called in the browser, it should

look like Figure 7-1.

Figure 7-1

To instantly change the appearance of this page without changing the style of each server control on the

page, you simply apply one of the ASP.NET default themes from within the Page directive:

<%@Page Language="VB" Theme="SmokeAndGlass" %>

Adding the Theme attribute to the Page directive changes the appearance of everything on the page that

is defined in the SmokeAndGlass theme file provided with ASP.NET 2.0. When you invoke the page in

the browser, you see the result shown in Figure 7-2.

Page 79: ASP.NET

Figure 7-2

Applying a theme to an entire application

In addition to applying an ASP.NET 2.0 predefined theme to your ASP.NET pages using

the Themeattribute within the Page directive, you can also apply it at an application level from

the web.configfile. This is illustrated in Listing 7-2.

Listing 7-2: Applying a theme application-wide from the web.config file

1. <?xml version="1.0" encoding="UTF-8" ??>

2.  

3. <configuration>

4. <system.web>

5. <pages theme="SmokeAndGlass" />

6. </system.web>

7. </configuration>

If you specify the theme in the web.config file, you don't need to define the theme again in

the Pagedirective of your ASP.NET pages. This theme is applied automatically to each and every page

within your application.

Applying a theme to all applications on a server

If you want to take it even one level higher, you can specify the theme that you want to use within

themachine.config file. This is illustrated in Listing 7-3.

Listing 7-3: Specifying the theme in the machine.config file

Page 80: ASP.NET

1. <pages buffer="true" enableSessionState="true"

2. enableViewState="true" enableViewStateMac="true"

3. autoEventWireup="true" validateRequest="true"

4. enablePersonalization="false" theme="SmokeAndGlass" >...

5. </pages>

The machine.config file is located atC:\WINDOWS\Microsoft.NET\Framework\v2.0.xxxxx\

CONFIG. The pages node is about one-third of the way through the file. Adding the Theme attribute to

the pages node within themachine.config file causes every Web application on that server to use the

specified theme. This is a great solution if the server has multiple applications that should all be using the

same theme.

If you set a theme in the machine.config file, you are not in any way required to use this theme for all

the applications on the server. To override the theme setting placed in the machine.config file, you just

specify another theme in the application's web.config file or in the Web page's Pagedirective.

Remember settings that are set in the web.config file override settings that are in

themachine.config file. Settings that are placed in the Page directive override both settings in

themachine.config and in the web.config files.

Removing themes from server controls

Whether themes are set on a server, at the application level, or on a page, at times you want an

alternative to the theme that has been defined. For example, change the text box server control that you

have been working with (from Listing 7-1) by making its background black and using white text:

1. <asp:Textbox ID="TextBox1" Runat="server"

BackColor="#000000" ForeColor="#ffffff" />

The black background color and the color of the text in the text box are specified directly in the control

itself with the use of the BackColor and ForeColor attributes. If you have applied a theme to the page

where this text box control is located, however, you won't see this black background or white text because

these changes are overridden by the theme itself.

To apply a theme to your ASP.NET page but not to this text box control, you simply use

theEnableTheming property of the text box server control:

1. <asp:Textbox ID="TextBox1" Runat="server"

BackColor="#000000" ForeColor="#ffffff" EnableTheming="false" />

If you apply this control to the text box server control from Listing 7-1 with the SmokeAndGlass theme

applied to the entire page, the theme is applied to every control on the page except the text box. This

result is shown in Figure 7-3.

Page 81: ASP.NET

Figure 7-3

If you want to turn off theming for multiple controls within a page, consider using the Panel control to

encapsulate a collection of controls and then set the EnableTheming attribute of the Panel control

toFalse. This disables theming for each control contained within the Panel control.

Differences between Web site Project and Web Application Project

Scenarios in which Web application projects are the preferred choice include the following:

You want to be able to use the Edit and Continue feature of the Visual Studio debugger.

You want to run unit tests on code that is in the class files that are associated with ASP.NET pages.

You want to refer to the classes that are associated with pages and user controls from standalone classes.

You want to establish project dependencies between multiple Web projects.

You want the compiler to create a single assembly for the entire site.

You want control over the assembly name and version number that is generated for the site.

You want to use MSBuild or Team Build to compile the project. For example, you might want to add pre-build and post-build steps.

Page 82: ASP.NET

You want to avoid putting source code on a production server.

You want to use the automated deployment tools that are available in Visual Studio 2010.

Scenarios in which Web site projects are the preferred choice include the following:

You want to include both C# and Visual Basic code in a single Web project. (By default, a Web application is compiled based on language settings in the project file. Exceptions can be made, but it is relatively difficult.)

You want to open the production site in Visual Studio and update it in real time by using FTP.

You do not want to have to explicitly compile the project in order to deploy it.

If you do precompile the site, you want the compiler to create multiple assemblies for the site, which can include one assembly per page or user control, or one or more assemblies per folder.

You want to be able to update individual files in production by just copying new versions to the production server, or by editing the files directly on the production server.

If you precompile the site, you want to be able to update individual ASP.NET Web pages (.aspx files) without having to recompile the entire Web site.

You like to keep your source code on the production server because it can serve as an additional backup copy.

Summary of Differences

The following table summarizes the main differences.

Area Web application projects

Web site projects

Project file structure

A Visual Studio project file (.csproj or .vbproj) stores information about the project, such as the list of files that are included in the project, and any project-to-project

There is no project file (.csproj or .vbproj). All the files in a folder structure are automatically included in the site.

Page 83: ASP.NET

references.

Compilation

You explicitly compile the source code on the computer that is used for development or source control.

By default, compilation of code files (excluding .aspx and .ascx files) produces a single assembly.

The source code is typically compiled dynamically (automatically) by ASP.NET on the server the first time a request is received after the site has been installed or updated.

You can precompile the site (compile in advance on a development computer or on the server).

By default, compilation produces multiple assemblies.

Namespaces

Explicit namespaces are added to pages, controls, and classes by default.

Explicit namespaces are not added to pages, controls, and classes by default, but you can add them manually.

Deployment

You copy the assembly to a server. The assembly is produced by compiling the application.

Visual Studio provides tools that integrate with the IIS Web deployment tool to automate many deployment tasks.

You copy the application source files to a computer that has IIS installed on it.

If you precompile the site on a development computer, you copy the assemblies produced by compilation to the IIS server.

Visual Studio provides tools for deployment, but they do not automate as many deployment tasks as the tools available for Web application projects.