Nothing Special   »   [go: up one dir, main page]

C# Jscript J#

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

ASP.

NET - Introduction
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
applications 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 bilateral communication and cooperation.

ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled 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 can be written in any of the following languages:

 C#
 Visual Basic.Net
 Jscript
 J#

ASP.NET is used to produce interactive, data-driven web applications over the internet. It
consists of a large number of controls such as 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 information obtained from various pages the user visited and
worked with, i.e., the overall session state. To clear the concept, let us take an example of a
shopping cart.

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

The ASP.NET Component Model

The ASP.NET component model provides various building blocks of ASP.NET pages. Basically
it is an object model, which describes:

 Server side counterparts of almost all HTML elements or tags, such as <form> and
<input>.

 Server controls, which help in developing complex user-interface. For example, the
Calendar control or the Gridview control.

ASP.NET is a technology, which works on the .Net framework that contains all web-related
functionalities. The .Net framework is made of an object-oriented hierarchy. An ASP.NET web
application is made of pages. When a user requests an ASP.NET page, the IIS delegates the
processing of the page to the ASP.NET runtime system.

The ASP.NET runtime transforms the .aspx page into an instance of a class, which inherits from
the base class page of the .Net framework. Therefore, each ASP.NET page is an object and all its
components i.e., the server-side controls are also objects.

What is ASP.NET - Part 1


ASP.NET is a Web application framework developed by Microsoft to build dynamic data
driven Web applications and Web services. 
1. ASP.NET is a subset of .NET framework. In simple terms a framework is a collection of
classes. 
2. ASP.NET is the successor to classic ASP (Active Server Pages).

What other technologies can be used to build web applications


1. PHP
2. Java
3. CGI
4. Ruby on Rails
5. Perl

What is a Web Application?


A web application is an application that is accessed by users using a web
browser. Examples of web browsers include 
1. Microsoft Internet Explorer
2. Google Chrome
3. Mozilla FireFox
4. Apple Safari
5. Netscape Navigator

What are the advantages of Web applications?


1. Web Applications just need to be installed only on the web server, where as desktop
applications need to be installed on every computer, where you want to access them.
2. Maintenance, support and patches are easier to provide.
3. Only a browser is required on the client machine to access a web application.
4. Accessible from anywhere, provided there is internet.
5. Cross Platform

How Web applications work?


1. Web applications work on client/server architecture
2. On the client all you need is a browser, that can understand HTML
3. On the server side, the Web application runs under Microsoft Internet Information
Services (IIS)

When the client enters the URL of the web application in the browser, and submits the
request. The web server which hosts the web application, receives the request. The
request is then processed by the application. The application generates, the HTML and
hands it over to the IIS (web server). Finally, IIS sends the generated HTML to the
client, who made the initial request. The client browser will the interpret the HTML and
displays the user interface. All this communication, happens over the internet using
HTTP protocol. HTTP stands for Hyper Text Transfer Protocol. A protocol is a set of
rules that govern how two or more items communicate.

Components of .Net Framework


Before going to the next session on Visual Studio.Net, let us go through at the various
components of the .Net framework 3.5. The following table describes the components of the .Net
framework 3.5 and the job they perform:

Components and their Description

(1) Common Language Runtime or CLR

It performs memory management, exception handling, debugging, security checking, thread


execution, code execution, code safety, verification, and compilation. The code that is directly
managed by the CLR is called the managed code. When the managed code is compiled, the
compiler converts the source code into a CPU independent intermediate language (IL) code. A
Just In Time(JIT) compiler compiles the IL code into native code, which is CPU specific.

(2) .Net Framework Class Library


It contains a huge library of reusable types. classes, interfaces, structures, and enumerated values,
which are collectively called types.

(3) Common Language Specification

It contains the specifications for the .Net supported languages and implementation of language
integration.

(4) Common Type System

It provides guidelines for declaring, using, and managing types at runtime, and cross-language
communication.

(5) Metadata and Assemblies

Metadata is the binary information describing the program, which is either stored in a portable
executable file (PE) or in the memory. Assembly is a logical unit consisting of the assembly
manifest, type metadata, IL code, and a set of resources like image files.

(6) Windows Forms

Windows Forms contain the graphical representation of any window displayed in the application.

(7) ASP.NET and ASP.NET AJAX

ASP.NET is the web development model and AJAX is an extension of ASP.NET for developing
and implementing AJAX functionality. ASP.NET AJAX contains the components that allow the
developer to update data on a website without a complete reload of the page.

(8) ADO.NET

It is the technology used for working with data and databases. It provides access to data sources
like SQL server, OLE DB, XML etc. The ADO.NET allows connection to data sources for
retrieving, manipulating, and updating data.

(9) Windows Workflow Foundation (WF)

It helps in building workflow-based applications in Windows. It contains activities, workflow


runtime, workflow designer, and a rules engine.

(10) Windows Presentation Foundation


It provides a separation between the user interface and the business logic. It helps in developing
visually stunning interfaces using documents, media, two and three dimensional graphics,
animations, and more.

(11) Windows Communication Foundation (WCF)

It is the technology used for building and executing connected systems.

(12) Windows CardSpace

It provides safety for accessing resources and sharing personal information on the internet.

(13) LINQ

It imparts data querying capabilities to .Net languages using a syntax which is similar to the
tradition query language SQL.

Common Language Runtime (CLR) manages the execution of .NET programs. The just-in-time
compiler converts the compiled code into machine instructions. This is what the computer
executes.

The services provided by CLR include memory management, exception handling, type safety,
etc.

Let us see the features of Common Language Runtime (CLR) in C#:

Components

Components in other languages can be easily worked upon with CLR.

Threading

The CLR provides support for threads to create multithreaded applications.

Class Library Support

It has built-in types and libraries for assemblies, threading, memory management, etc.

Debugging

CLR makes code debugging easier.


Garbage Collection

It provides automatic garbage collection in C#.

The implications of the CLR are wide-ranging:

Deep language integration:

VB and C#, like all .NET languages, compile to IL. In other words, the CLR makes no
distinction between different languages—in fact, it has no way of knowing what language was
used to create an executable. This is far more than mere language compatibility; it’s language
integration.

Side-by-side execution:

The CLR also has the ability to load more than one version of a component at a time. In other
words, you can update a component many times, and the correct version will be loaded and used
for each application. As a side effect, multiple versions of the .NET Framework can be installed,
meaning that you’re able to upgrade to new versions of ASP.NET without replacing the current
version or needing to rewrite your applications.

Fewer errors:

Whole categories of errors are impossible with the CLR. For example, the CLR prevents many
memory mistakes that are possible with lower-level languages such as C++.

.NET Framework Class Library


.NET Framework Class Library is the collection of classes, namespaces, interfaces and value
types that are used for .NET applications.

It contains thousands of classes that supports the following functions.

 Base and user-defined data types


 Support for exceptions handling
 input/output and stream operations
 Communications with the underlying system
 Access to data
 Ability to create Windows-based GUI applications
 Ability to create web-client and server applications
 Support for creating web services

.NET Framework Class Library Namespaces

Following are the commonly used namespaces that contains useful classes and interfaces and
defined in Framework Class Library.
Namespaces Description
System It includes all common datatypes, string
values, arrays and methods for data
conversion.
System.Windows.Forms, System.Windows.Forms.Design These namespaces are used to create
Windows-based applications using
Windows user interface components.
System.Web, System.Web.UI, System.Web.UI.Design, These are used to create ASP. NET Web
System.Web.UI.WebControls, System.Web.UI.HtmlControls, applications that run over the web.
System.Web.Configuration,

C# - Basic Syntax
C# is an object-oriented programming language. In Object-Oriented Programming methodology,
a program consists of various objects that interact with each other by means of actions. The
actions that an object may take are called methods. Objects of the same kind are said to have the
same type or, are said to be in the same class.

For example, let us consider a Rectangle object. It has attributes such as length and width.
Depending upon the design, it may need ways for accepting the values of these attributes,
calculating the area, and displaying details.

Let us look at implementation of a Rectangle class and discuss C# basic syntax −

using System;

namespace RectangleApplication {
class Rectangle {

// member variables
double length;
double width;

public void Acceptdetails() {


length = 4.5;
width = 3.5;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result −

Length: 4.5
Width: 3.5
Area: 15.75

The using Keyword

The first statement in any C# program is

using System;

The using keyword is used for including the namespaces in the program. A program can include
multiple using statements.

The class Keyword

The class keyword is used for declaring a class.

Comments in C#

Comments are used for explaining code. Compilers ignore the comment entries. The multiline
comments in C# programs start with /* and terminates with the characters */ as shown below −

/* This program demonstrates


The basic syntax of C# programming
Language */

Single-line comments are indicated by the '//' symbol. For example,

}//end class Rectangle

Member Variables

Variables are attributes or data members of a class, used for storing data. In the preceding
program, the Rectangle class has two member variables named length and width.

Member Functions

Functions are set of statements that perform a specific task. The member functions of a class are
declared within the class. Our sample class Rectangle contains three member functions:
AcceptDetails, GetArea and Display.

Instantiating a Class

In the preceding program, the class ExecuteRectangle contains the Main() method and
instantiates the Rectangle class.
Identifiers

An identifier is a name used to identify a class, variable, function, or any other user-defined item.
The basic rules for naming classes in C# are as follows −

 A name must begin with a letter that could be followed by a sequence of letters, digits (0
- 9) or underscore. The first character in an identifier cannot be a digit.

 It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ]
{ } . ; : " ' / and \. However, an underscore ( _ ) can be used.

 It should not be a C# keyword.

Value Type and Reference Type


C# includes following categories of data types:

1. Value type
2. Reference type

Value Type:

A data type is a value type if it holds a data value within its own memory space. It means
variables of these data types directly contain their values.

All the value types derive from System.ValueType, which in-turn, derives from System.Object.

For example, consider integer variable int i = 100;

The system stores 100 in the memory space allocated for the variable 'i'. The following image
illustrates how 100 is stored at some hypothetical location in the memory (0x239110) for 'i':

Memory allocation for Value Type .The following data types are all of value type:

 bool
 byte
 char
 decimal
 double
 enum
 float
 int
 long
 sbyte
 short
 struct
 uint
 ulong
 ushort

Passing by Value:

When you pass a value type variable from one method to another method, the system creates a
separate copy of a variable in another method, so that if value got changed in the one method
won't affect on the variable in another method.

using System;

public class Program


{
static void ChangeValue(int x)
{
x = 200;

Console.WriteLine(x);
}
public static void Main()
{
int i = 100;

Console.WriteLine(i);

ChangeValue(i);

Console.WriteLine(i);
}
}
Output:
100
200
100

In the above example, variable i in Main() method remains unchanged even after we pass it to the
ChangeValue() method and change it's value there.

Reference Type

Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address
where the value is being stored. In other words, a reference type contains a pointer to another
memory location that holds the data.

For example, consider following string variable:

string s = "Hello World!!";

The following image shows how the system allocates the memory for the above string variable.
Memory allocation for
Reference type

As you can see in the above image, the system selects a random location in memory (0x803200)
for the variable 's'. The value of a variable s is 0x600000 which is the memory address of the
actual data value. Thus, reference type stores the address of the location where the actual value is
stored instead of value itself.

The following data types are of reference type:

 String
 All arrays, even if their elements are value types
 Class

Pass by Reference

When you pass a reference type variable from one method to another, it doesn't create a new
copy; instead, it passes the address of the variable. If we now change the value of the variable in
a method, it will also be reflected in the calling method.

using System;
public class Student{

public string StudentName { get; set; }

}
public class Program
{
public static void ChangeReferenceType(Student std2)
{
std2.StudentName = "Steve";
}

public static void Main()


{
Student std1 = new Student();

std1.StudentName = "Bill";

ChangeReferenceType(std1);

Console.WriteLine(std1.StudentName);
}
}
Output:
Steve

C# - Type Conversion
Type conversion is converting one type of data to another type. It is also known as Type Casting.
In C#, type casting has two forms −

 Implicit type conversion − These conversions are performed by C# in a type-safe


manner. For example, are conversions from smaller to larger integral types and
conversions from derived classes to base classes.
 Explicit type conversion − These conversions are done explicitly by users using the pre-
defined functions. Explicit conversions require a cast operator.

The following example shows an explicit type conversion

using System;

namespace TypeConversionApplication {
class ExplicitConversion {
static void Main(string[] args) {
double d = 5673.74;
int i;

// cast double to int.


i = (int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result −

5673

C# Type Conversion Methods

C# provides the following built-in type conversion methods −


Sr.No Methods & Description
.
1 ToBoolean
Converts a type to a Boolean value, where possible.
2 ToByte
Converts a type to a byte.
3 ToChar
Converts a type to a single Unicode character, where possible.
4 ToDateTime
Converts a type (integer or string type) to date-time
structures.
5 ToDecimal
Converts a floating point or integer type to a decimal type.
6 ToDouble
Converts a type to a double type.
7 ToInt16
Converts a type to a 16-bit integer.
8 ToInt32
Converts a type to a 32-bit integer.
9 ToInt64
Converts a type to a 64-bit integer.
10 ToSbyte
Converts a type to a signed byte type.
11 ToSingle
Converts a type to a small floating point number.
12 ToString
Converts a type to a string.
13 ToType
Converts a type to a specified type.
14 ToUInt16
Converts a type to an unsigned int type.
15 ToUInt32
Converts a type to an unsigned long type.
16 ToUInt64
Converts a type to an unsigned big integer.

The following example converts various value types to string type −

using System;

namespace TypeConversionApplication {
class StringConversion {
static void Main(string[] args) {
int i = 75;
float f = 53.005f;
double d = 2345.7652;
bool b = true;

Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
Console.WriteLine(d.ToString());
Console.WriteLine(b.ToString());
Console.ReadKey();

}
}
}

When the above code is compiled and executed, it produces the following result −

75
53.005
2345.7652
True

C# - Loops
There may be a situation, when you need to execute a block of code several number of times. In
general, the statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated
execution paths.

A loop statement allows us to execute a statement or a group of statements multiple times and
following is the general from of a loop statement in most of the programming languages −

C# provides following types of loop to handle looping requirements. Click the following links to
check their detail.

Sr.No Loop Type & Description


.
1 while loop

It repeats a statement or a group of statements while a given condition is true. It tests the
condition before executing the loop body.

A while loop statement in C# repeatedly executes a target statement as long as a given


condition is true.

Syntax

The syntax of a while loop in C# is −


while(condition) {
statement(s);
}

Here, statement(s) may be a single statement or a block of statements. The condition


may be any expression, and true is any non-zero value. The loop iterates while the
condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.

Flow Diagram

Here, key point of the while loop is that the loop might not ever run. When the condition
is tested and the result is false, the loop body is skipped and the first statement after the
while loop is executed.

Example
using System;

namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;

/* while loop execution */


while (a < 20) {
Console.WriteLine("value of a: {0}", a);
a++;
}
Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

2 for loop

It executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

Syntax

The syntax of a for loop in C# is −


for ( init; condition; increment ) {
statement(s);
}

Here is the flow of control in a for loop −

 The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here,
as long as a semicolon appears.

 Next, the condition is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and flow of control jumps to the
next statement just after the for loop.

 After the body of the for loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after
the condition.

 The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again testing
for a condition). After the condition becomes false, the for loop terminates.

Flow Diagram
Example
using System;

namespace Loops {
class Program {
static void Main(string[] args) {

/* for loop execution */


for (int a = 10; a < 20; a = a + 1) {
Console.WriteLine("value of a: {0}", a);
}
Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
3 do...while loop
It is similar to a while statement, except that it tests the condition at the end of the loop
body

Syntax

The syntax of a do...while loop in C# is −


do {
statement(s);
} while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s)
in the loop execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in
the loop execute again. This process repeats until the given condition becomes false.

Flow Diagram

Example

using System;

namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;

/* do loop execution */
do {
Console.WriteLine("value of a: {0}", a);
a = a + 1;
}
while (a < 20);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.

C# provides the following control statements. Click the following links to check their details.

Sr.No Control Statement & Description


.
1 break statement

Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
2 continue statement

Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.

C# provides an easy to use and more readable alternative to for loop, the
foreach loop when working with arrays and collections to iterate through the
items of arrays/collections. The foreach loop iterates through each item,
hence called foreach loop.

Syntax of foreach loop


foreach (element in iterable-item)
{
// body of foreach loop
}

Here iterable-item can be an array or a class of collection.

How foreach loop works?

The in keyword used along with foreach loop is used to iterate over the iterable-item. The in
keyword selects an item from the iterable-item on each iteration and store it in the variable
element.

On first iteration, the first item of iterable-item is stored in element. On second iteration, the
second element is selected and so on.
The number of times the foreach loop will execute is equal to the number of elements in the
array or collection.

Printing array using foreach loop


using System;

namespace Loop
{
class ForEachLoop
{
public static void Main(string[] args)
{
char[] myArray = {'H','e','l','l','o'};

foreach(char ch in myArray)
{
Console.WriteLine(ch);
}
}
}
}

When we run the both program, the output will be:

H
e
l
l
o

In the above program, the foreach loop iterates over the array, myArray. On first iteration, the
first element i.e. myArray[0] is selected and stored in ch.

Similarly on the last iteration, the last element i.e. myArray[4] is selected. Inside the body of
loop, the value of ch is printed.

When we look at both programs, the program that uses foreach loop is more readable and easy to
understand. This is because of its simple and expressive syntax.

Hence, foreach loop is preferred over for loop when working with arrays and collections.

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

The ASP.NET life cycle could be divided into two groups:

 Application Life Cycle


 Page Life Cycle
ASP.NET Application Life Cycle

The application life cycle has the following stages:

 User makes a request for accessing application resource, a page. Browser sends this
request to the web server.

 A unified pipeline receives the first request and the following events take place:

o An object of the class ApplicationManager is created.

o An object of the class HostingEnvironment is created to provide information


regarding the resources.

o Top level items in the application are compiled.

 Response objects are created. The application objects such as HttpContext, HttpRequest
and HttpResponse are created and initialized.

 An instance of the HttpApplication object is created and assigned to the request.

 The request is processed by the HttpApplication class. Different events are raised by this
class for processing the request.

ASP.NET Page Life Cycle

When a page is requested, it is loaded into the server memory, processed, and sent to the
browser. Then it is unloaded from the memory. At each of these steps, methods and events are
available, which could be overridden according to the need of the application. In other words,
you can write your own code to override the default code.

The Page class creates a hierarchical tree of all the controls on the page. All the components on
the page, except the directives, are part of this control tree. You can see the control tree by
adding trace= "true" to the page directive. We will cover page directives and tracing under
'directives' and 'event handling'.

The page life cycle phases are:

 Initialization
 Instantiation of the controls on the page
 Restoration and maintenance of the state
 Execution of the event handler codes
 Page rendering

Understanding the page cycle helps in writing codes for making some specific thing happen at
any stage of the page life cycle. It also helps in writing custom controls and initializing them at
right time, populate their properties with view-state data and run control behavior code.

Following are the different stages of an ASP.NET page:

 Page request - When ASP.NET gets a page request, it decides whether to parse and
compile the page, or there would be a cached version of the page; accordingly the
response is sent.
 Starting of page life cycle - At this stage, the Request and Response objects are set. If
the request is an old request or post back, the IsPostBack property of the page is set to
true. The UICulture property of the page is also set.

 Page initialization - At this stage, the controls on the page are assigned unique ID by
setting the UniqueID property and the themes are applied. For a new request, postback
data is loaded and the control properties are restored to the view-state values.

 Page load - At this stage, control properties are set using the view state and control state
values.

 Validation - Validate method of the validation control is called and on its successful
execution, the IsValid property of the page is set to true.

 Postback event handling - If the request is a postback (old request), the related event
handler is invoked.

 Page rendering - At this stage, view state for the page and all controls are saved. The
page calls the Render method for each control and the output of rendering is written to
the OutputStream class of the Response property of page.

 Unload - The rendered page is sent to the client and page properties, such as Response
and Request, are unloaded and all cleanup done.

ASP.NET Page Life Cycle Events

At each stage of the page life cycle, the page raises some events, which could be coded. An event
handler is basically a function or subroutine, bound to the event, using declarative attributes such
as Onclick or handle.

Following are the page life cycle events:

 PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack property
and determines whether the page is a postback. It sets the themes and master pages,
creates dynamic controls, and gets and sets profile property values. This event can be
handled by overloading the OnPreInit method or creating a Page_PreInit handler.

 Init - Init event initializes the control property and the control tree is built. This event can
be handled by overloading the OnInit method or creating a Page_Init handler.

 InitComplete - InitComplete event allows tracking of view state. All the controls turn on
view-state tracking.

 LoadViewState - LoadViewState event allows loading view state information into the
controls.

 LoadPostData - During this phase, the contents of all the input fields are defined with
the <form> tag are processed.

 PreLoad - PreLoad occurs before the post back data is loaded in the controls. This event
can be handled by overloading the OnPreLoad method or creating a Page_PreLoad
handler.
 Load - The Load event is raised for the page first and then recursively for all child
controls. The controls in the control tree are created. This event can be handled by
overloading the OnLoad method or creating a Page_Load handler.

 LoadComplete - The loading process is completed, control event handlers are run, and
page validation takes place. This event can be handled by overloading the
OnLoadComplete method or creating a Page_LoadComplete handler

 PreRender - The PreRender event occurs just before the output is rendered. By handling
this event, pages and controls can perform any updates before the output is rendered.

 PreRenderComplete - As the PreRender event is recursively fired for all child controls,
this event ensures the completion of the pre-rendering phase.

 SaveStateComplete - State of control on the page is saved. Personalization, control state


and view state information is saved. The HTML markup is generated. This stage can be
handled by overriding the Render method or creating a Page_Render handler.

 UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad
event for all controls recursively and lastly for the page itself. Final cleanup is done and
all resources and references, such as database connections, are freed. This event can be
handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.

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

ASP.NET runtime controls the association between a page instance and its state. An ASP.NET
page is an object of the Page 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 object page 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 environment for the page to run. The @Page directive defines
page-specific attributes used by ASP.NET page parser and compiler. Page directives specify how
the page should be processed, and which assumptions need to be taken about the page.

It allows importing namespaces, loading assemblies, and registering new controls with custom
tag names and namespace prefixes.
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 raise events
when some events take place on the user interface, like a user clicks a button or moves the
cursor. The kind of response these events need to reciprocate is coded in the event handler
functions. The event handlers 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.

HTML Server Controls

The HTML server controls are basically the standard HTML controls enhanced to enable server
side processing. The HTML controls such as the header tags, anchor tags, and input elements are
not processed by the server but are sent to the browser for display.

They are specifically converted to a server control by adding the attribute runat="server" and
adding an id attribute to make them available for server-side processing.

For example, consider the HTML input control:

<input type="text" size="40">

It could be converted to a server control, by adding the runat and id attribute:

<input type="text" id="testtext" size="40" runat="server">

Advantages of using HTML Server Controls

Although ASP.NET server controls can perform every job accomplished by the HTML server
controls, the later controls are useful in the following cases:

 Using static tables for layout purposes.


 Converting a HTML page to run under ASP.NET
The following table describes the HTML server controls:

Control Name HTML tag


HtmlHead <head>element
HtmlInputButton <input type=button|submit|reset>
HtmlInputCheckbox <input type=checkbox>
HtmlInputFile <input type = file>
HtmlInputImage <input type = image>
HtmlInputPassword <input type = password>
HtmlInputRadioButto <input type = radio>
n
HtmlInputReset <input type = reset>
HtmlText <input type = text|password>
HtmlImage <img> element
HtmlLink <link> element
HtmlAnchor <a> element
HtmlButton <button> element
HtmlButton <button> element
HtmlForm <form> element
HtmlTable <table> element
HtmlTableCell <td> and <th>
HtmlTableRow <tr> element
HtmlTitle <title> element
HtmlSelect <select&t; element

Example

The following example uses a basic HTML table for layout. It uses some boxes for getting input
from the users such as name, address, city, state etc. It also has a button control, which is clicked
to get the user data displayed in the last row of the table.

The page should look like this in the design view:

The code for the content page shows the use of the HTML table element for layout.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"


Inherits="htmlserver._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>

<style type="text/css">
.style1
{
width: 156px;
}
.style2
{
width: 332px;
}
</style>

</head>

<body>
<form id="form1" runat="server">
<div>
<table style="width: 54%;">
<tr>
<td class="style1">Name:</td>
<td class="style2">
<asp:TextBox ID="txtname" runat="server"
style="width:230px">
</asp:TextBox>
</td>
</tr>

<tr>
<td class="style1">Street</td>
<td class="style2">
<asp:TextBox ID="txtstreet" runat="server"
style="width:230px">
</asp:TextBox>
</td>
</tr>

<tr>
<td class="style1">City</td>
<td class="style2">
<asp:TextBox ID="txtcity" runat="server"
style="width:230px">
</asp:TextBox>
</td>
</tr>

<tr>
<td class="style1">State</td>
<td class="style2">
<asp:TextBox ID="txtstate" runat="server"
style="width:230px">
</asp:TextBox>
</td>
</tr>

<tr>
<td class="style1"> </td>
<td class="style2"></td>
</tr>

<tr>
<td class="style1"></td>
<td ID="displayrow" runat ="server" class="style2">
</td>
</tr>
</table>

</div>
<asp:Button ID="Button1" runat="server" >Text="Click" />
</form>
</body>
</html>

The code behind the button control:

protected void Button1_Click(object sender, EventArgs e)


{
string str = "";
str += txtname.Text + "<br />";
str += txtstreet.Text + "<br />";
str += txtcity.Text + "<br />";
str += txtstate.Text + "<br />";
displayrow.InnerHtml = str;
}

Observe the following:

 The standard HTML tags have been used for the page layout.

 The last row of the HTML table is used for data display. It needed server side processing,
so an ID attribute and the runat attribute has been added to it.

You might also like