AWP Main
AWP Main
Written By
TYBsc-IT
Semester-V
Unit-III
Error Handling, Logging, and Tracing State Management Styles, Themes, and Master
Pages
Unit-IV
ADO.NET Fundamentals Data Binding The Data Controls
XML
Unit-V
Security Fundamentals ASP.NET AJAX
Index
Sr. No Topic Page No
1
3-40 Web Form
Introducing .NET C# Language Types, Objects, and Namespaces 2
Fundamentals
41-61 Error Handling, Logging, and Tracing
Form Controls 3
62-79
State Management Styles, Themes, and Master Pages
4
80-91
ADO.NET Fundamentals Data Binding The Data Controls
XML
5 Security Fundamentals
ASP.NET AJAX
92-107
2 | Salvi College Prof: Sonu Raj |[email protected] | 8080837038 |8976249271
Unit-I
Topics:
Base class
Library:
▪ Base class library is one of component of .Net Framework. It supplies a library of base classes that
we can use to implement applications quickly.
▪ Common Language Runtime (CLR) is the programming (Virtual Machine component) that
manages the execution of programs written in any language that uses the .NET Framework, for
example C#, VB.Net, F# and so on.
▪ Programmers write code in any language, including VB.Net, C# and F# then they compile their
programs into an intermediate form of code called CLI in a portable execution file (PE) that can be
managed and used by the CLR and then the CLR converts it into machine code to be will executed
by the processor.
▪ The information about the environment, programming language, its version and what class libraries
will be used for this code are stored in the form of metadata with the compiler that tells the CLR how
to handle this code.
▪ The CLR allows an instance of a class written in one language to call a method of the class written
in another language.
Components of the
CLR:
CTS Common Type System (CTS) describes a set of types that can be used in different .Net
languages in common. That is, the Common Type System (CTS) ensure that objects written in
different .Net languages can interact with each other. For Communicating between programs
written in any .NET complaint language, the types must be compatible on the basic level. These
types can be Value Types or Reference Types. The Value Types are passed by values and
stored in the stack. The Reference Types are passed by references and stored in the heap.
CLS CLS stands for Common Language Specification and it is a subset of CTS. It defines a set
of rules and restrictions that every language must follow which runs under .NET framework. The
languages which follow these set of rules are said to be CLS Compliant. In simple words, CLS
enables cross-language integration or Interoperability.
For Example if we take C-Sharp and VB.net in C# each statement must have to end with a
semicolon it is also called a statement Terminator but in VB.NET each statement should not end
with a semicolon (;). So, these syntax rules which we have to follow from language to language
differ but CLR can understand all the language Syntax because in.NET each language is
converted into MSIL code after compilation and the MSIL code is language specification of CLR.
MSIL
Instead, we compile our code into Microsoft Intermediate Language (MSIL) code. The MSIL
code is not specific to any operating system or to any language.
Advantages -
• MSIL provide language interoperability as code in any .net language is compiled on
MSIL
• Same performance in all .net languages
• support for different runtime environments
• JIT
compiler in CLR converts MSIL code into native machine code which is executed
by OS
Functions of the
CLR
A namespace is designed for providing a way to keep one set of names separate from
another. The class names declared in one namespace does not conflict with the same class
names declared in another.
Defining a
Namespace
A namespace definition begins with the keyword namespace followed by the namespace
name as follows:
namespace
namespace_name {
// code
declarations }
Example:
using System;
namespace first_space
{ class namespace_cl {
} } namespace
second_space { class
namespace_cl { public
void func()
{ Console.WriteLine("Inside
second_space");
} } } class TestClass {
} } The using
Keyword
The using keyword states that the program is using the names in the given namespace. For
example, we are using the System namespace in our programs. The class Console is defined
there. We just write:
System.Console.WriteLine("Hello
there");
Alias of
Namespace:
using A=System.Console;
Main() { A.Write("Craetion of
Alias"); A.ReadKey();
}
}
▪ Value types
▪ Reference types
▪ Pointer types
Value Type
Value type variables can be assigned a value directly. They are derived from the class
System.ValueType.
The value types directly contain data. Some examples are int, char, and float, which stores
numbers, alphabets, and floating-point numbers, respectively. When you declare an int type, the
system allocates memory to store the value.
Reference Type
The reference types do not contain the actual data stored in a variable, but they contain a
reference to the variables.
In other words, they refer to a memory location. Using multiple variables, the reference types
can refer to a memory location. If the data in the memory location is changed by one of the
variables, the other variable automatically reflects this change in value. Example of built-in
reference types are: object, dynamic, and string.
8 | Salvi College Prof: Sonu Raj |[email protected] | 8080837038 |8976249271
Q5. Explain the implicit and explicit conversion of data types with
examples.
▪ The process of converting from one data type to another data type is called
conversion.
o The two types are compatible. o The destination type has a range
that is greater than the source type.
▪ When these two conditions are met, a widening conversion takes place. For example, the int type
is always large enough to hold all valid byte values, and both int and byte are compatible integer
types, so an implicit conversion can be applied.
▪ For widening conversions, the numeric types, including integer and floating-point types, are
compatible with each other.
▪ For example, the following program is perfectly valid since long to double is a widening conversion
that is automatically performed.
Console.WriteLine("L and D: " + L + " " + D); } } Casting Incompatible Types Although
the
implicit type conversions are helpful, they will not fulfil all programming needs because they apply
only to widening conversions between compatible types. For all other cases we must employ a
cast. A cast is an instruction to the compiler to convert the outcome of an expression into a
specified type. Thus, it requests an explicit type conversion. A cast has this general form:
(target-type) expression
Here, target-type specifies the desired type to convert the specified expression to.
For Example
Here, even though x and y are of type double, the cast converts the outcome of the expression to
int. The parentheses surrounding x / y are necessary. Otherwise, the cast to Int would apply only
to the x and not to the outcome of the division.
The cast is necessary here because there is no implicit conversion from double to int. When a
cast involves a narrowing conversion, information might be lost.
Q6. Explain Boxing and Unboxing with reference to value type and
reference type.
Boxing: Any type, value or reference can be assigned to an object without explicit conversion.
When a compiler fined a value where it needs a reference type, it creates an object ‘box’ into
which it places the value of the value type.
Example: -
int m = 10; object om = m; When executed, this code creates a temporary reference _type ‘box’
for the object on heap. We can also use a C-style cast for boxing.
Note that the boxing operation creates a copy of the value of the m integer to the object om.
Both the variables exist but the value of om resides on the heap. This means that the values are
independent of each other.
Example
Unboxing:
Unboxing is the process of converting the object type back to the value type. Remember that a
variable can be unboxed only if it has been previously boxed. In contrast to boxing, unboxing is
an explicit operation.
Example:-
Logical operators Logical operators are used to combine two or more condition. Below is list of
logical operators used in C#.
The statements inside your source files are generally executed from top to bottom, in the order
that they appear. Control flow statements, however, break up the flow of execution by employing
decision making, looping, and branching, enabling your program to conditionally execute
particular blocks of code.
Break Statement
The break statement is used to exit from loops and switch statements. The break statement
terminates the execution control from a loop or a switch statement to the next statement after the
loop or switch statement.
The general format is:
triangle 1 1 2 1
23
Main() { for(int
i=1;i<=5;i++) { for(int
j=1;j<=5;j++) {
Console.Write(" "+j);
if(j==i) { break; }
} Console.WriteLine(" ");
} } } Continue
Statement
The continue statement causes early iteration of a loop. It skips the remaining statements
after the continue statement and moves the execution control to the next iteration of the loop.
using System; class demo { public static void Main() { for(int i=1;i<=25;i++) { if(i%2!=0) {
using System;
break.
Number 1 Number 2 Number 3
Number 4 Demonstrating the use
of continue. Number 1
▪ The switch statement is similar to if statement in that it executes code conditionally based on the
value of a test. However, switch enables us to test for multiple values of a test variable in one go,
rather than just a single condition.
▪ This test is limited to discrete values, rather than clauses such as ‘‘greater than X,’’ so its use is
slightly different; but it can be a powerful technique.
Console.ReadKey(); } } Q10.
Give syntax of foreach
loop. Explain with example.
A foreach loop mostly used with array and collection such ArrayList. A foreach loop enables
us to address each element in an array using this simple syntax:
foreach (<baseType><name> in <array>) { // can use <name> for each element } This loop will
cycle through each element, placing it in the variable <name> in turn, without danger of
accessing illegal elements. We don’t have to worry about how many elements are in the array,
and we can be sure that we get to use each one in the loop.
The main difference between using this method and a standard for loop is that foreach gives us
read- only access to the array contents, so we can’t change the values of any of the elements.
Example using System; class Abc static void Main(string[] args) { string[]
Console.WriteLine(friendName); } Console.ReadKey(); }
Afor loop executes a statement or a block of statements repeatedly until a specified expression
evaluates to false. There is need to specify the loop bounds (minimum or maximum).
Example:
int j = 0;
for (int i = 1; i <= 5; i++) { j= j + i ; } The foreach statement repeats a group of embedded
) { j = j + i ; }
OR
Explain jagged array with
example.
Jagged array is also called Array of Array or variable sized array. In a jagged array, each row
may have different number of columns.
Example
i=0;i<4;i++) { for(int
j=0;j<x[i].Length;j++) {
Console.Write(x[i][j]+"\t"); }
Console.Write("\n");
} }
Reference Parameter:
It is used as a call by reference in C#. It is used in both places; when we declare a method and
when we call the method. In this example we create a function (cube) and pass a ref parameter
in it, now we look at the value before we call the function and after we call the function.
classAbc { public void cube(ref int x) { x= x * x * x; } } class Program { static void
Parameter:
Sometimes we do not want to give an initial value to the parameter; in this case we use the out
parameter. The declaration of the out parameter is the same as the ref parameter. But it is used
to pass the value out of a method. Now we look at the
classAbc
a; return
b; } } class Program { static
Console.ReadLine();
} }
Q14. Is Multiple Main () allowed in C#?
Justify
We can use more than on Main Method in C# program, But there will only one Main Method
which will act as entry point for the program.
Main(string[] args) {
A"); Console.ReadLine();
} } class B {
B"); Console.ReadLine();
} } Try to
Classes created with the help of class keyword. Example:- struct Book { }
Example:- class Abc { }
Q16. Need of enumerator data type in C#
▪ An enum is a value type with a set of related named constants often referred to as an
enumerator list.
▪ The enum keyword is used to declare an enumeration. It is a primitive data type, which
is user defined.
▪ Enums type can be integer (float, int, byte, double etc.). But if you used beside int it
has to be cast.
▪ The keyword enum is used to create numeric constants in .NET framework.
▪ There must be a numeric value for each enum type.
▪ The default underlying type of the enumeration elements is int. By default, the first
enumerator has the value 0, and the value of each successive enumerator is increased
by 1.
Example:-
using System; enumDays {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
class Abc { public static void main() { Console.WriteLine((int)Days.Wed);
Console.WriteLine((Days)4); } }
Q17. Explain inheritance and polymorphism.
Inheritance Inheritance is the concept we use to build new classes using the existing
class definitions. Through inheritance we can modify a class the way we want to create
new objects. The original class is known as base or parent class & the modified class is
known as derived or subclass or child class. The
18 | Salvi College Prof: Sonu Raj |[email protected] | 8080837038 |8976249271
concept of inheritance facilitates the reusability of existing code & thus improves the integrity of
programs & productivity of programmers.
Polymorphism Polymorphism is the ability to take more than one form. For example, an
operation may exhibit different behavior in different situations. The behavior depends upon the
types of data used on the operation. Polymorphism is extensively used while implementing
inheritance.
Q18. What are sealed classes and sealed methods? Why are
they used?
The methods declared with a sealed keyword in its header are known as sealed methods. Such
method provides a complete implementation to its base class virtual method using the override
keyword.
Characteristics
▪ A method cannot be defined as sealed unless that method is an override of a method in its base
class.
▪ A sealed method cannot be overridden further.
▪ Sealed methods are useful to avoid problems caused by overriding the existing
functionality.
▪ It prevents the user from changing the internal functionality of a
class.
Example:
Console.WriteLine("A.F"); }
Console.WriteLine("A.G"); } }
Console.WriteLine("B.F"); }
Console.WriteLine("B.G"); } }
class C: B
{ override public void G() { Console.WriteLine("C.G"); } } The class B provides two override
▪ Generally if we create classes we can inherit the properties of that created class in any class
without having any restrictions.
▪ In some situation we will get requirement like we don’t want to give permission for the users to
derive the classes from it or don’t allow users to inherit the properties from particular class.
▪ For that purpose we have keyword called “sealed” in
OOPS.
▪ When we defined class with keyword “Sealed” then we don’t have a chance to derive that
particular class and we don’t have permission to inherit the properties from that particular class.
▪ A sealed class cannot be inherited.
▪ It is an error to use a sealed class as a base
class.
▪ Use the sealed modifier in a class declaration to prevent inheritance of the
class.
▪ It is not permitted to use the abstract modifier with a sealed
class.
Example:
using System;
Q19. What are the rules in defining a constructor? Explain static constructor with
example.
Rules for
constructor:
▪ A constructor should have the same name as that of its
class.
Static Constructor:
static classname()
{
//static member initializations; } ▪ Also note that a static constructor is parameter less and no
Example:
Main() { } }
Q20. Explain various Types of Constructors
in C#
Default and
Parameterized
▪ When constructor does not accept any parameter then it is referred as default constructor or
zero parametrized.
Example:
{ Console.WriteLine("default cons"); }
//Console.WriteLine("paramaterized cons");
length = l; breadth = b; } public double
Private constructor
▪ Private constructors are used to restrict the instantiation of object using ‘new’ operator.
▪ A private constructor is a special instance constructor. It is commonly used in classes that
contain static members only.
▪ This type of constructors is mainly used for creating singleton object.
▪ If you don't want the class to be inherited we declare its constructor private.
Example:
test() { Console.WriteLine("private
Constructor
Example:
test.show(); Console.ReadLine();
} }
C# does not support multiple inheritance. However, you can use interfaces to implement
multiple inheritance. The following program demonstrates this:
Example:
setHeight(int h) { height = h;
Rectangle(); int
area;
Rect.getCost(area)); Console.ReadKey(); } } }
▪ C# does not support multiple inheritances, but a class has the option of implementing one or
more interfaces.
▪ One challenge with interfaces is that they may include methods that have the same signatures as
existing class members or members of other interfaces.
▪ Explicit interface implementations can be used to disambiguate class and interface methods that
would otherwise conflict.
▪ Explicit interfaces can also be used to hide the details of an interface that the class developer
considers private.
▪ To explicitly implement an interface member, just use its fully qualified name in the
declaration.
▪ A fully qualified interface name takes the form
InterfaceName.MemberName
Example:
void I2.A() {
Similarities:
▪ Both abstract classes and interfaces may contain members that can be inherited by a derived
class.
Differences:
▪ Derived classes may only inherit from a single base class, which means that only a single abstract
class can be inherited directly. Conversely, classes can use as many interfaces as they want
▪ Abstract classes may possess both abstract members and non-abstract members. Interface
members conversely, must be implemented on the class that uses the interface they do not possess
code bodies.
▪ Moreover, interface members are by definition public but members of abstract classes may also
be private (as long as they aren’t abstract), protected, internal, or protected internal. In addition,
interfaces can’t contain fields, constructors, destructors, static members, or constants.
Example:
Console.ReadKey(); } }
Overloading Method Overloading means having two or more methods with the same name but
with different signature (different parameters list and different type of parameters) in same class
or in different classes. Method Overloading forms compile-time polymorphism.
Overriding Method overriding means having two methods with same name and same signature,
one method in base class and other method in derived class.
A subclass inherits methods from a base class. Sometimes, it is necessary for the subclass to
modify the methods defined in the base class. This is referred to as method overriding.
This can be achieved by using the virtual and override keywords. We have to use the virtual
keyword for the method which in base class and override keyword for the method in subclass.
By default functions are not virtual in C# and so you need to write “virtual”
explicitly.
Q26. Explain method hiding with
example.
In a C# program a derived class can have methods with the same signature as that of its base
class methods. This hides the base class methods by its derived class counterparts and gives a
warning.
This warning can be suppressed by using the new keyword with the derive class methods. This
means that the members of the base class are made intentionally hidden by the members
having the same signature in the derived class. The new function will never be invoked by a
base class pointer.
Example:-
class demo
In method overriding we can override a method in base class by creating similar method in
derived class this can be achieved by using inheritance principle and using “virtual & override”
keywords.
If we want to override base class method then we need to declare base class method with
“virtual” keyword and the method which we created in derived class to override base class need
to declare with “override” keyword like as shown below
Example:-
Console.WriteLine("Sample A Test
Console.WriteLine("Sample B Test
Main(string[] args)
{ SampleA a=new
SampleA(); SampleB
b=new SampleB();
a.Show(); b.Show(); a =
new SampleB(); a.Show();
Console.ReadLine(); } } }
Hiding methods:
To hide base class methods in derived classes we can declare derived class methods with new
keyword. To use new keyword, we need to write the code like as shown below
Example:-
class SampleA { public void Show() {
Console.WriteLine("Sample A Test
Console.WriteLine("Sample B Test
SampleA(); SampleB
b=new SampleB();
a.Show(); b.Show(); a = new SampleB();
a.Show(); Console.ReadLine(); } }
Derived class The functionality of an existing class can be extended by creating a new class
from it. The new class is then called a child class or derived class. The derived class inherits the
properties of the base class.
Abstract class
Static class
A static class is class whose objects cannot be created and must contain only static
members.
Sealed class
A sealed class is a class which cannot be inherited. In C#, the sealed modifier is used to define
a class as sealed.
Partial class
It is possible to split the definition of a class over two or more source files. Each source file
contains a section of the type or meth
An assembly in ASP.NET is a collection of single-file or multiple files. The assembly that has
more than one file contains either a dynamic link library (DLL) or an EXE file. The assembly also
contains metadata that is known as assembly manifest.
The assembly manifest contains data about the versioning requirements of the assembly, author
name of the assembly, the security requirements that the assembly requires to run, and the
various files that form part of the assembly.
The biggest advantage of using ASP.NET Assemblies is that developers can create applications
without interfering with other applications on the system. When the developer creates an
application that requires an assembly that assembly will not affect other applications.
The assembly used for one application is not applied to another application. However, one
assembly can be shared with other applications. In this case the assembly has to be placed in the
bin directory of the application that uses it.
This is in contrast to DLL in the past. Earlier developers used to share libraries of code through
DLL. To use the DLL that is developed by another developer for another application, we must
register that DLL in our machine. In ASP.NET, the assembly is created by default whenever we
build a DLL. We can check the details of the manifest of the assembly by using classes located in
the System.Reflection namespace.
Thus, we can create two types of ASP.NET Assemblies in ASP.NET: private ASP.NET
Assemblies and shared assemblies. Private ASP.NET Assemblies are created when you build
component files like DLLs that can be applied to one application.
Shared ASP.NET Assemblies are created when you want to share the component files across
multiple applications. Shared ASP.NET Assemblies must have a unique name and must be
placed in Global Assembly Cache (GAC). The GAC is located in the Assembly directory in
WinNT. You can view both the manifest and the IL using ILDisassembler (ildasm.exe).
The manifest file contains all the metadata needed to specify the assembly's version
requirements, security identity, and all metadata needed to define the scope of the assembly
and resolve references to resources and classes.
Components of
Assembly
Manifest It describes the assembly. The manifest file contains all the metadata needed to
specify the assembly's version requirements, security identity, and all metadata needed to
define the scope of the assembly and resolve references to resources and classes.
Type Metadata It contains metadata, which describes each type (class, structure,
enumeration, and so forth)
Every time our application instantiates a reference-type object, the CLR allocates space on the
managed heap for that object.
However, we never need to clear this memory manually. As soon as our reference to an object
goes out of scope (or our application ends), the object becomes available for garbage collection.
The garbage collector runs periodically inside the CLR, automatically reclaiming unused memory
for inaccessible objects.
The .NET Framework provides automatic memory management called garbage collection. A
.NET program that runs in a managed environment is provided with this facility by .NET CLR
(common language runtime).
It is called only when the CLR decides that it is most needed. It happens in a situation such as
the heap for the given process is becoming full and requires a clean-up.
In the common language runtime (CLR), the garbage collector serves as an automatic
memory manager. It provides the following benefits:
GC.Collect ()
method:
▪ This method is used to call garbage collector explicitly. It is used to force a garbage collection to
occur at any time.
Namespaces are C# program elements designed to help you organize our programs. They also
provide assistance in avoiding name clashes between two sets of code. Implementing
Namespaces in our own code is a good habit because it is likely to save us from problems later
when we want to reuse some of our code.
For example, if we created a class named Console, we would need to put it in our own
namespace to ensure that there wasn't any confusion about when the System.Console class
should be used or when our class should be used. Generally, it would be a bad idea to create a
class named Console, but in many cases your classes will be named the same as classes in
either the .NET Framework Class Library or namespaces help us to avoid the problems that
identical class names would cause.
System is fundamental namespace for C# application. It contains all the fundamental classes
and base classes which are required in simple C# application. These classes and sub classes
defines reference data type, method and interfaces. Some classes provide some other feature
like data type conversion, mathematical function.
Alias of namespace
Main() { A.Write(“Welcome to
C# !!!!”); } }
▪ The System namespace contains fundamental classes and base classes that define
commonly-used value and reference data types, events and event handlers, interfaces, attributes,
and processing exceptions.
▪ The System.Collections namespace contains interfaces and classes that define various
collections of objects, such as lists, queues, bit arrays, hash tables and dictionaries.
▪ The System.Data namespace provides access to classes that represent the ADO.NET
architecture. ADO.NET lets you build components that efficiently manage data from multiple data
sources.
▪ The System.Drawing parent namespace contains types that support basic GDI+ graphics
functionality.
Collection: Collections are basically group of records which can be treated as a one
logical unit. .NET Collections are divided in to four important categories as follows.
▪ Indexed based.
▪ Key Value Pair.
▪ Prioritized Collection.
▪ Specialized Collection.
Indexed based: It helps us to access the value by using generated index
number by the collection.
Key Value Pair: It helps you to access value by the user defined
key.
Specialized Collection: It is very specific collections which are meant for very specific purpose
like hybrid dictionary that start as list and become Hashtable.
ArrayList is a non-generic type of collection in C#. It can contain elements of any data types. It is
similar to an array, except that it grows automatically as you add items in it. Unlike an array, we
don't need to specify the size of ArrayList.
Console.WriteLine(myArryList.Contains(100)
);
public MyGenericClass(T
value) {
genericMemberVariable =
value; }
public T genericMethod(T
genericParameter) {
Console.WriteLine("Parameter type: {0}, value: {1}",
typeof(T).ToString(),genericParameter); Console.WriteLine("Return type: {0}, value: {1}",
typeof(T).ToString(), genericMemberVariable);
return genericMemberVariable;
}
int val =
intGenericClass.genericMethod(200);
As we can see in the above code, MyGenericClass is defined with <T>. <> indicates that
MyGenericClass is generic and the underlying type would be defined later, for now consider it as
T. We can take any character or word instead of T. Output: Parameter type: int, value: 200
Return type: int, value: 10
In C#, data encapsulation is possible through either classes or structures. By using various
access modifiers like private, public, protected, internal etc it is possible to control the
accessibility of the class members. Usually inside a class, we declare a data field as private and
will provide a set of public SET and GET methods to access the data fields. In C#, properties are
defined using the property declaration syntax. The general form of declaring a property is as
MyClass();
Delegate:
The dictionary meaning of ‘Delegates’ is “A person acting for another person”. A delegate in C#
is a class type object & is used to invoke a method that has been encapsulated into it at the time
of its creation.
} }
When same delegate is used to call method multiple time then it is referred as Multicast
delegate or Multiple delegate.
Example
} Q41. Delegates in C# are used for Event Handling. Justify this statement with a
event event-delegate
event-name;
Here, event-delegate is the name of the delegate used to support the event, and event-name is
the name of the specific event object being declared.
Example:
using System;
MyEvent(); evt.SomeEvent
+= Handler;
evt.OnSomeEvent(); } }
ASP.NET File Types: - ASP.NET applications can include many types of files. Below table
show list of files.
File Name Description .aspx These are ASP.NET web pages. They contain the user interface
and, optionally, the underlying application code. Users request or navigate directly to one of
these pages to start our web application .ascx These are ASP.NET user controls. User controls
are similar to web pages, except that the user can’t access these files directly. Instead, they
must be hosted inside an ASP.NET web page. User controls allow you to develop a small piece
of user interface and reuse it in as many web forms as you want without repetitive code.
web.config This is the configuration file for your ASP.NET application. It includes settings for
customizing security, state management, memory management, and much more. global.asax
This is the global application file. You can use this file to define global variables (variables that
can be accessed from any web page in the web application) and react to global events (such as
when a web application first starts). .cs These are code-behind files that contain C# code. They
allow you to
separate the application logic from the user interface of a web page.
ASP.NET Web Folders. Every web application starts with a single location, called the root
folder. However, in a large, well-planned web application.
Directory Description App_Code Contains source code files that are dynamically compiled for
use in
our application App_GlobalResources Stores global resources that are accessible to every page
in the web application. This directory is used in localization scenarios, when we need to have a
website in m ore than one language. App_Data Stores data, including SQL Server Express database
files App_Themes Stores the themes that are used to standardize and reuse
formatting in our web application.
Presentation Layer The presentation layer consists of the Asp.net page that manages the
appearance of application. This layer can include bound data controls and ObjectDataSource
objects that bind data controls to the data.
Middle Layer The middle layer contains the data access classes that manage the data access
for the application. This layer can also contain business objects that represent business entities
such as customers, products or employee and that implement business rules such as credit and
discount policies.
Database Layer
This layer consists of the database that contains the data for the application. Ideally the SQL
statement that do the database access should be saved in stored procedure within the
database, nut the SQL statement are often stored in the data access classes.
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.
Page initialization At this stage, the controls on the page are assigned unique ID by setting the
UniqueID property and themes are applied.
Validation Validate method of the validation control is called and if it runs successfully, 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 called.
Page rendering At this stage, view state for the page and all
controls are saved.
Unload The rendered page is sent to the client and page properties, such as Response and
Request are unloaded and all cleanup done.
PreInit() Init()
InitComplete()
LoadViewState()
LoadPostData()
PreLoad() Load()
LoadComplete()
PreRender()
PreRenderComplete()
SaveStateComplete()
UnLoad()
▪ The Global.asax file does not need recompilation if no changes have been made to it. There can
be only one Global.asax file per application and it should be located in the application's root
directory only.
Application_BeginRequest() – This event raised at the start of every request for the web application.
Application_EndRequest() – This event raised at the end of each request right before the objects
released. Application_PreRequestHandlerExecute() – This event called before the appropriate
HTTP handler executes the request. Application_PostRequestHandlerExecute() – T his event
called just after the request is handled by its appropriate HTTP handler.
Application_Start() – This event raised when the application starts up and application domain is
created. Session_Start() – This event raised for each time a new session begins, This is a good
place to put code that is session-specific. Application_Error() – This event raised whenever an
unhandled exception occurs in the application. This provides an opportunity to implement
generic application-wide error handling. Session_End() – This event called when session of user
pplication_End() – This event raised just before when web application ends.
ends. A
Application_Disposed() – This event fired after the web application is destroyed and this event is
used to reclaim the memory it occupies.
Web.Config
▪ Configuration file is used to manage various settings that define a website. The settings are
stored in XML files that are separate from our application code. In this way we can configure
settings independently from our code.
▪ Generally a website contains a single Web.config file stored inside the application root directory.
However there can be many configuration files that manage settings at various levels within an
application.
▪ There are number of important settings that can be stored in the configuration file. Some of the
most frequently used configurations, stored conveniently inside Web.config file are:
- Database connections -
Caching settings - Session
States - Error Handling -
Security
This is an input control which is used to take user input. To create TextBox either we can write code
or use the drag and drop facility of visual studio IDE. This is server side control, asp provides own
tag to create it. The example is given below. < asp:TextBoxID="TextBox1" runat="server"
></asp:TextBox>
This control has its own properties that are tabled below.
TextMode It used to determine behavior of control. Possible value are Single / Multiline
/ Password
Example: Assign a text to TextBox control when Button click event fires
using c#
C# code for above TextBox ExampleC# protected void
Q9. What is the difference between buttons, Link Buttons and Image Buttons? Explain any
three
common button attributes.
These controls differ only in how they appear to the user. A button displays text within a rectangular
area. A Link button displays text that look like a hyperlink and an image button displays an image.
LinkButton control is a control just like a Button control along with the flexibility to make it look like a Hyperlink. It
implements an anchor <a/> tag that uses only ASP.NET postback mechanism to post the data on the server. Despite
being a hyperlink, we can't specify the target URL. ImageButton control is used to post the form or fire an event
either client side or server side. It’s like a asp:Button control, the only difference is, we have the ability to place our
own image as a
Button control is used to post the form or fire an event either client side or server side. Button control is generally
used to post the form or fire an event either client side or server side. When it is rendered on the page, it is generally
implemented through <input type=submit> HTML tag.
Q10. Explain CheckBox and RadioButton web server controls in
ASP.NET.
CheckBox: CheckBox control is an asp.net web server control. CheckBox control visually as square
on web forms. The Checkbox control allow user to check square or uncheck square. In CheckBox
control check and uncheck checkbox specify by the checked property of check box true or false.
Basic syntax for check box: <asp:CheckBox ID= "chkoption" runat=
"Server"></asp:CheckBox>
CheckBox properties:
▪ AutoPostBack:Specifies whether the form should be posted immediately after the Checked property
has changed or not. Default is false
▪ CausesValidation:Specifies if a page is validated when a Button control is clicked
▪ Checked:Specifies whether the check box is checked or not
▪ Id:A unique id for the control
▪ Text: The text next to the check box
RadioButton Radiobutton isasp.net web server control. Radiobutton is used to allow user to select a
single radiobutton from group of radiobutton. In asp.net generally we use more than one radiobutton
and select only one radiobutton at a time from all the radiobutton control. On other hand in checkbox
control we can check and uncheck multiple check box at a time.
RadioButton properties:
▪ AutoPostBack:A Boolean value that specifies whether the form should be posted immediately after
the Checked property has changed or not. Default is false
▪ Checked : A Boolean value that specifies whether the radio button is checked or not id a unique id
for the control
▪ GroupName : The name of the group to which this radio button belongs
▪ Text : The text next to the radio button
ListBox control is an asp.net web server control. ListBox control used to store the multiple items and
allow user to select multiple item from ListBox control. ListBox control is same as dropdownlist
control. The dropdownlist control allow user to select maximum only one item at a time, on other
hand ListBox control allow user to select multiple items same time. So we can also say ListBox is
multi- row selection box control. In a ListBox control there is a SelectionMode property to change the
mode of section from single to multiple. By default ListBox control selection mode is single if we want
to select multiple items from ListBox, then just change the SelectionMode property to multiple.
GetSelectedIndices
▪ Gets the array of index values for currently selected items in the ListBox
control.
▪ public virtual int[] GetSelectedIndices()
▪ Say for example, if ID of the list box is ‘ListBox1’ then the following code displays all selected
items from the list box to a label with ID ‘Label1’.
OnSelectedIndexChange
d
Q12. What is the difference between List Box and Drop-Down Lists? List and explain any
three common
properties of these
controls.
▪ List boxes are used in cases where there are small numbers of items to be selected. In contrast,
drop-down lists are typically used with larger list so that they don’t take up much space on the
page.
▪ A list box lets a user select one or more items from the list of items. A drop-down list lets a user
choose an item from the drop-down list of items.
Properties Description Items Gets the collection of items from the dropdown
box. SelectedValue Get the value of the Selected item from the dropdown box.
SelectedIndex Gets or Sets the index of the selected item in the dropdown box.
SelectedItem Gets the selected item from the list.
Sorted The Sorted property set to true, the ListBox items are sorted. The following code snippet
sorts the ListBox items.
listBox1.Sorted = true;
SelectionMode property defines how items are selected in a ListBox. The SelectionMode value
can be one of the following four SelectionMode enumeration values. None - No item can be
selected. One - Only one item can be selected. MultiSimple - Multiple items can be selected.
MultiExtended - Multiple items can be selected, and the user can use the SHIFT, CTRL, and
arrow keys to make selections.
listBox1.SelectionMode =
SelectionMode.MultiSimple;
listBox1.SetSelected(1, true);
listBox1.SetSelected(2, true);
MultiColumn: A multicolumn ListBox places items into as many columns as are needed to
make vertical scrolling unnecessary. The user can use the keyboard to navigate to columns that
are not currently visible. Set the HorizontalScrollbar property to true to display a horizontal scroll
bar that enables the user to scroll to columns that are not currently shown in the visible region of
the ListBox. The value of the ColumnWidth property determines the width of each column.
listBox1.MultiColumn = true;
SelectedItem Gets or sets the currently selected item in the ListBox. We can get text associated
with currently selected item by using Items property.
string selectedItem =
listBox1.Items[listBox1.SelectedIndex].ToString();
listBox1.SelectedIndex = 1;
Table control is used to structure a web pages. In other words to divide a page into several rows
and columns to arrange the information or images. When it is rendered on the page, it is
implemented through <table> HTML tag.
We can simply use HTML <table> control instead of using <asp:Table> control. However many of
one benefits of using <asp:Table> control is we can dynamically add rows or columns at the
runtime or change the appearance of the table. Following are some important properties that are
very useful. BackImageUrl Used to set background image of the table Caption Used to write the
caption of the table.
Example:
ASP.NET code for a table control
<asp:Table ID="Table1" runat="server" Height="123px" Width="567px">
<asp:TableRow runat="server">
<asp:TableCell runat="server"></asp:TableCell>
<asp:TableCell runat="server"></asp:TableCell>
<asp:TableCell runat="server"></asp:TableCell>
</asp:TableRow> <asp:TableRow runat="server">
<asp:TableCell runat="server"></asp:TableCell>
<asp:TableCell runat="server"></asp:TableCell>
<asp:TableCell runat="server"></asp:TableCell>
</asp:TableRow>
MltiView control is a container of several view control. In a multiview control there are many view
control for designing separation of view for user.
The View control is a container of several web server controls. Using the multiview control we
can feel the multiple page view design on a single web page.
We can also say multiview control allow user to create different view on single web page. There
are many view control in a multiview control, each view control has some web server control for
design web page. We can see single view at a time on web page by specify the
ActiveViewIndex property of multiview control.
All view control assign automatically index to all it, the index always start from zero. The first
view1 index is zero, second is one and so on, If we want to display first view on web page,
then we need to write MultiView1.ActiveViewIndex=0.
• Prefix for MultiView control is mv
• Prefix
for View control is v The MultiView control
has the following important properties:
Adrotator control display the sequence of images, which is specified in the external XML file. In
xml file we indicate the images to display with some other attributes, like image impressions,
NavigateUrl, ImageUrl, AlternateText.
ASP.NET provides a Calendar control that is used to display a calendar on the Web page. This
control displays a one-month calendar that allows the user to select dates and move to the next
and previous months.
By default, this control displays the name of the current month, day headings for the days of the
weeks, days of the month and arrow characters for navigation to the previous or next month.
The class hierarchy for this control is as follows
Object->Control->WebControl->Calendar
The Calendar is complex, powerful Web server control that you can use to add calendar
feature to our web page. We can use calendar control display any date between 0 A.D. and
9999A.D.The Calendar control is represented as:
The Calendar control when rendered to a user browser, it generates an HTML <table> element
and a set of associated JavaScript. The Calendar control can be used to select a single date or
multiple dates. The SelectionMode property is used for this. The SelectionMode properties are
as:
Example
Web server controls are created on the server and they require a runat="server" attribute to
work. This attribute indicates that the control should be treated as a server control.
We cannot send special characters through query string. All special characters should be
encoded when you pass them through the query string. The encoded string must be decoded at
the receiver. There are two methods to achieve this: UrlEncode and UrlDecode():
The main purpose of these two methods is to encode and decode the URLrespectively. We
need to encode the URL because some of the characters are not safe sending those across
browser. Some characters are being misunderstood by the browser and that leads to data
mismatch on the receiving end. Characters such as a question mark (?), ampersand (&), slash
mark (/), and spaces might be truncated or corrupted by some browsers.
UrlDecode() This method is used to decode the encoded URL string. Decodes any %##
encoding in the given string. Syntax: UrlDecode (string str )
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
described in a previous chapter, so instead of caching an entire page, we may cache only the
UserControl, so that the rest of the page is still re-loaded on each request. Creation of
UserControl: Following steps are used to create UserControl.
1. Open Visual Studio. 2. "File" -> "New" -> "Project..." then select ASP.NET Webform
Application. 3. Add a new web form. To create a new UserControl, in Solution Expolrer, Add
New Item, provide your File Name and click Add Design UserControl as per our requirement.
Next step to use UserControl in .aspx page. Add the following line below the standard page
declaration:
<%@RegisterTagPrefix="My"TagName="UserInfoBoxControl"Src="~/UserInfoBoxCont rol.ascx"
%>
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:UserInfoBoxControlrunat="server"ID="MyUserInfoBoxControl"/>
Validation is important part of any web application. User's input must always be validated before
sending across different layers of the application.
▪ RequiredFieldValidation Control
▪ CompareValidator Control
▪ RangeValidator Control
▪ RegularExpressionValidator Control
▪ CustomValidator Control
▪ ValidationSummar
RequiredFieldValidator
Control
The RequiredFieldValidator control is simple validation control, which checks to see if the data is
entered for the input control. We can have a RequiredFieldValidator control for each form
element on which you wish to enforce Mandatory Field rule.
RangeValidator
Control
The RangeValidator Server Control is another validator control, which checks to see if a control
value is within a valid range. The attributes that are necessary to this control are:
MaximumValue, MinimumValue, and Type.
</asp:RangeValidator>
RegularExpressionValidat
or
</asp:RegularExpressionValidato
r
Q25. What is the use of Compare Validator? Explain it along with its
properties.
CompareValidator
Control
▪ The CompareValidator control allows you to make comparison to compare data entered in an
input control with a constant value or a value in a different control.
▪ It can most commonly be used when you need to confirm password entered by the user at
the registration time. The data is always case sensitive.
▪ It has the following specific properties:
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 />
The CustomValidator control allows writing application specific custom validation routines for
both the client side and the server-side validation.
The server-side validation routine must be called from the control's ServerValidate event
handler. The server-side validation routine should be written in any .Net language, like C# or
VB.Net.
Example:
In this below example we will simply check the length of the string in the
TextBox.
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 />
ServerValidateEventArgs e) { if(e.Value.Length == 8)
e.IsValid =
true; else
control in ASP.NET
The Menu control is used to create a menu of hierarchical data that can be used to navigate
through the pages. The Menu control conceptually contains two types of items. First is
StaticMenu that is always displayed on the page, second is DynamicMenu that appears when
opens the parent item.
Following steps are used to create Menu Control: Toolbox > Navigation
> Menu or add the following few lines of code snippet.
▪ ASP.NET TreeView Web control is used to display hierarchical data (such as a table of
contents) in a tree structure in a Web page.
▪ The TreeView control is made up of TreeNode objects. The TreeView control can be bound to
data.
▪ Automatic data binding, this allows the nodes of the control to be bound to hierarchical data,
such as an XML document.
▪ Site navigation support through integration with the SiteMapDataSource
control.
▪ Node text that can be displayed as either selectable text or
hyperlinks.
▪ Customizable appearance through themes, user-defined images, and
styles.
▪ Programmatic access to the TreeView object model, which allows you to dynamically create
trees, populates nodes, set properties, and so on.
▪ Node population through client-side callbacks to the server (on supported
browsers).
▪ The ability to display a check box next to each
node.
▪ Each node in the Tree is represented by a name/value pair (not necessarily unique), defined by
the Text and Value properties of TreeNode, respectively. The text of a node is rendered, whereas
the value of a node is not rendered and is typically used as additional data for handling postback
events.
▪ This example also uses the ExpandDepth property of TreeView to automatically expand the tree
1 level deep when it is first rendered.
▪ The TreeView control is made up of one or more nodes. Each entry in the tree is called a node
and is represented by a TreeNode
▪ The SiteMapPath control basically is used to access web pages of the website from one
webpage to another. It is a navigation control and displays the map of the site related to its web
pages.
▪ This map includes the pages in the particular website and displays the name of those pages.
We can click on that particular page in the Site Map to navigate to that page. We can say that the
SiteMapPath control displays links for connecting to URLs of other pages.
▪ The SiteMapPath control uses a property called SiteMapProvider for accessing data from
databases and it stores the information in a data source.
Root Node->Child
Node
ParentLevelsDisplayed : It specifies the number of levels of parent nodes and then displays
the control accordingly related to the currently displayed node. RenderCurrentNodeAsLink : It
specifies whether or not the site navigation node that represents the currently displayed page is
rendered as a hyperlink. PathSeperator : It specifies the string that displays the SiteMapPath
nodes in the rendered navigation path. Style properties of the SiteMapPath class
CurrentNodeStyle : It specifies the style used for the display text for the current
node.
NodeStyle : It specifies the style used for the display text for all nodes in the site navigation
path.
Sitemap file has been included in our project and we can see it in the Solution Explorer. And
now we have to set the URL and title attributes in the sitemap file. <?xml version="1.0"
encoding="utf-8" ?> <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="Default.aspx" title="myhomepage" description="">
<siteMapNode url="myweb1.aspx" title=" myfirstpage" description="" /> <siteMapNode
url="myweb2.aspx" title="mysecondpage" description="" /> </siteMapNode> </siteMap>
The status code sent from the server, each time the page is requested shows the name and
time of error if any. The following table shows the common HTTP status codes: The class of a
status code can be quickly identified by its first digit:
1xx: Informational
2xx: Success 3xx:
Redirection 4xx:
Client Error 5xx:
Server Error
Under the top level information, there is Trace log, which provides details of page life
cycle. It provides elapsed time in seconds since the page was initialized.
63 | Salvi College Prof: Sonu Raj |[email protected] | 8080837038 |8976249271
To check the Warn method, let us forcibly enter some erroneous code in the selected index
changed event handler: try { int a = 0; int
b = 9 / a; } catch (Exception e) { Trace.Warn("UserAction",
"processing 9/a", e); } Try-Catch is a C# programming construct. The try block holds any code that may
Application level tracing applies to all the pages in the web site. It is implemented by putting the
following code lines in the web.config file: <system.web> <trace enabled="true" /> </system.web>
Error Handling Although ASP.NET can detect all runtime errors, still some subtle errors may
still be there. Observing the errors by tracing is meant for the developers, not for the users. Hence, to
intercept such occurrence, we can add error handing settings in the web.config file of the application.
It is application-wide error handling. For example, we can add the following lines in the web.config
file: <configuration> <system.web>
</system.web>
<configuration>
When debugging is enabled, the following lines of codes are shown in the
web.config:
Breakpoints Breakpoints specifies the runtime to run a specific line of code and then stop execution
so that the code could be examined and perform various debugging jobs such as, changing the
value of the variables, step through the codes, moving in and out of functions and methods etc.
To set a breakpoint, right click on the code and choose insert break point. A red dot appears on the
left margin and the line of code is highlighted as shown:
Next when you execute the code, you can observe its
behavior.
At this stage, you can step through the code, observe the execution flow and examine the value of
the variables, properties, objects, etc. We can modify the properties of the breakpoint from the
Properties menu obtained by right clicking the breakpoint glyph:
Q3. Why exception handling is required? Write syntax for user define
exception?
Basic syntax:
try { //programming logic(code which may give rise to exceptions) } catch (Exception e) {
//message on exception } finally { // always executes } Try:A try block identifies a block of code
Finally:The finally block is used to execute a given set of statements, whether an exception is
thrown or not thrown. For example, if you open a file, it must be closed whether an exception is
raised or not.
Example:
using System; class tryCatch { public static void Main() { int k=0; try
{ int n=
10/k; Console.WriteLine(”n=”
+ n); } catch(Exception e) { Console .WriteLine
class Student {
public int StudentID { get; set; } public string
InvalidStudentNameException : Exception {
public InvalidStudentNameException()
{}
public InvalidStudentNameException(string
name)
: base(String.Format("Invalid Student Name: {0}",
try {
newStudent = new Student();
newStudent.StudentName =
"James007";
ValidateStudent(newStudent); }
catch(InvalidStudentNameException
ex) {
Console.WriteLine(ex.Message );
}
Console.ReadKey()
;}
if (!regex.IsMatch(std.StudentName))
throw new
InvalidStudentNameException(std.StudentName); } }
▪ If the information that we want to be accessed or stored globally throughout the application, even if
multiple users access the site or application at the same time, then we can use an Application
Object for such purposes.
▪ It stores information as a Dictionary Collection in key - value pairs. This value is accessible across
the pages of the application / website.
▪ There are 3 events of the Application which are as follows
Application_Start
Application_Error
Application_End
Example - Just for an example, I am setting the Page title in the Application Start event of the
Global.asax file. Code for setting value to the Application Object - "PageTitle" is the Key and
"Welcome to State Management Application" is the value.
▪ Query String is the most simple and efficient way of maintaining information across
requests.
▪ The information we want to maintain will be sent along with the URL. A typical URL with a query
string looks like www.somewebsite.com/search.aspx?query=foo
▪ The URL part which comes after the? Symbol is called a
QueryString.
Response.Redirect("foo.aspx?id=1&name=fo
o");
String id = Request.QueryString["id"];
String name =
Request.QueryString["name"];
▪ The HtmlEncode() method is particularly useful if you’re retrieving values from a database and
you aren’t sure if the text is valid HTML.
▪ We can use the HtmlDecode() method to revert the text to its normal form if we need to perform
additional operations or comparisons with it in your code.
▪ The UrlEncode() method changes text into a form that can be used in a URL, escaping spaces
and other special characters. This step is usually performed with information we want to add to the
query string. Label1.Text = Server.HtmlEncode("To bold text use the <b> tag."); Advantages
▪ Query string is lightweight and will not consume any server
resources.
▪ It is very easy to use, and it is the most efficient state management technique. However, it has
many Disadvantages
▪ A cookie is a small piece of information stored on the client machine. This file is located on client
machines "C:\Document and Settings\Currently_Login user\Cookie" path.
▪ It is used to store user preference information like Username, Password, City and Phone No etc.
on client machines. We need to import namespace called Systen.Web.HttpCookie before we use
cookie. Types of Cookies:
Persist Cookie - A cookie has not had expired time which is called as Persist
Cookie
Creation of cookies:
It’s really easy to create a cookie in the Asp.Net with help of Response object or
HttpCookie
Example 1:
Example 2:
Response.Cookies["userName"].Value =
"Annathurai";
Its easy way to retrieve cookie value form cookes by help of Request
object.
Example 1:
Example 2:
When we make request from client to web server, the web server process the request and give
the lot of information with big pockets which will have Header information, Metadata, cookies
etc., Then repose object can do all the things with browser.
Cookie's common
property:
Disadvantages of
Cookie
Q8. Write a program to create a new cookie with the name “Username” and add it to the
HttpResponse object on the click of a button. Set the expiry date of the cookie to One year
from Now.
"WELCOME"); Username.Expires=DateTime.Now.AddYears(1);
Response.Cookies.Add(Username); }
▪ View State is the method to preserve the Value of the Page and Controls between round trips. It is
a Page-Level State Management technique.
▪ View State is turned on by default and normally serializes the data in every control on the page
regardless of whether it is actually used during a post-back.
Advantages of View
State
▪ Easy to Implement.
▪ No server resources are required: The View State is contained in a structure within the page
load.
▪ Enhanced security features: It can be encoded and compressed or Unicode
implementation.
Disadvantages of View
State
▪ Security Risk: The Information of View State can be seen in the page output source directly. We
can manually encrypt and decrypt the contents of a Hidden Field, but It requires extra coding. If
security is a concern, then consider using a Server-Based State Mechanism so that no sensitive
information is sent to the client.
▪ Performance: Performance is not good if we use a large amount of data because View State is
stored in the page itself and storing a large value can cause the page to be slow.
▪ Device limitation: Mobile Devices might not have the memory capacity to store a large
amount of View State data.
▪ It can store values for the same page only.
Example:
The following code shows storing a value in an application variable and reading
from it.
We should get a basic knowledge about the events associated with application and
session.
▪ Application_Start This event executes when application initializes. This will execute when
ASP.NET worker process recycles and starts again.
▪ Application_End Executes when the application
ends.
▪ Session_Start Executes when a new session
starts.
▪ Session_End Executes when session ends. Note: this event will be fired only if you are using
InProc as session mode.
Example
The most common usage of application variables is to count the active number of visitors
that are browsing currently.
Application["activeVisitors"] = 0; } void
(Application["activeVisitors"] != null) {
Application.Lock(); int
visitorCount =
(int)Application["activeVisitors"];
Application["activeVisitors"] = visitorCount++;
Application.UnLock(); } }
▪ Data stored in session will be kept in server memory and it is protected as it will never get
transmitted to a client.
▪ Every client that uses the application will have separate sessions. Session state is ideal for storing
user specific information.
Working of
Session:
▪ ASP.NET maintains a unique id which is called as "session id" for each session. This id is
generated using a custom algorithm and it is unique always.
▪ Session id will be sent to the client as a cookie and the browser resends this upon each
request.
▪ ASP.NET uses this session id to identify the session
object.
string sessionId =
Session.SessionID
Session State
▪ Session state is user and browser specific.
Application State
▪ Application state is application specific.
▪ Application state is stored only in the memory on the server.
▪ Application state does not track client's cookies or URL.
▪ Application state has no scope to the current browser. If we change the browser application
id remains same.
▪ External CSS
▪ Internal CSS or Embedded
CSS
▪ Inline CSS
External Style Sheet The first way to add CSS style sheets to your web pages is through the
<link> element that points to an external CSS file.
For example the following <link> shows what options you have when embedding a style sheet in
your page:
The href property points to a file within our site when we create links between two pages. The rel
and type attributes tell the browser that the linked file is in fact a cascading style sheet. The
media attribute enables us to target different devices, including the screen, printer, and handheld
devices. The default for the media attribute is screen, so it’s OK.
Embedded style sheet The second way to include style sheets is using embedded <style>
elements. The <style> element should be placed at the top of your ASPX or HTML page,
between the <head> tags.
For example, to change the appearance of an <h1> element in the current page alone, we can
add the following code to the <head> of our page:
<head runat=”server”>
<style type=”text/css”> h1
Inline style sheet The third way to apply CSS to your HTML elements is to use inline styles.
Because the style attribute is already applied to a specific HTML element, we don’t need a
selector and we can write the declaration in the attribute directly:
With a Type selector all HTML elements of that type will be styled accordingly. h1 { color: Green;
} This Type selector now applies to all <h1> elements in your code and gives them a green
ID Selector The ID selector is always prefixed by a hash symbol (#) and enables us to refer to a
single element in the page. Within an HTML or ASPX page, we can give an element a unique ID
using the id attribute. With the ID selector, we can change the behavior for that single element,
for example:
#IntroText {
font-style: italic;
} Because we can reuse this ID across multiple pages in our site (it only must be unique within a
single page),
you can use this rule to quickly change the appearance of an element that you use
once per page, but more than once in our site, for example with the following HTML code:
Class Selector
The Class selector enables us to style multiple HTML elements through the class attribute. This
is handy when we want to give the same type of formatting to several unrelated HTML elements.
The following rule changes the text to red and bold for all HTML elements that have their class
attributes set to highlight:
make the contents of a <span> element and a link (<a>) appear with a bold typeface: This is
normal text but <span class=”Highlight”>this is Red and Bold.</span> This is also normal text
but <a href=”CssDemo.aspx” class=”Highlight”>this link is Red and Bold as well.</a>
▪ The HTML <link> tag is used for defining a link to an external document. It is placed in the
<head> section of the document.
Where,
▪ rel-can be used to specify the relationship of the target of the link to the current page.
▪ type-This attribute Provides information about the content type of the destination resource, telling
wether it's an HTML document, a JPG image, an Excel document, etc.
▪ href(uri)-The "href" attribute specifies the destination resource, which the element is linking to. It may
specify a resource in the same website or in an external one.
A theme decides the look and feel of the website. It is a collection of files that define the looks of
a page. It can include skin files, CSS files & images.
We define themes in a special App_Themes folder. Inside this folder is one or more subfolders
named Theme1, Theme2 etc. that define the actual themes. The theme property is applied late in
the page's life cycle, effectively overriding any customization we may have for individual controls on
our page. There are 3 different options to apply themes to our website: 1 . Setting the theme at the
page level: The Theme attribute is added to the page directive of the page.
<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="Default"T
heme="Theme1"%>
2. Setting the theme at the site level: to set the theme for the entire website we can set the theme
in
the web.config of the website. Open the web.config file and locate the <pages> element and
add the theme attribute to it: <pagestheme="Theme1"> .... .... </pages>
3. Setting
the theme programmatically at runtime: here the theme is set at runtime through coding.
It should be applied earlier in the page's life cycle ie. Page_PreInit event should be handled for
setting the theme. The better option is to apply this to the Base page class of the site as every
page in the site inherits from this class.
Add an ASP.Net Themes Folder To use the themes in the web site, we need to add an ASP.Net Themes
folder by right-clicking on Solution Explorer as in the following:
After adding the theme folder, add the SkinFile.skin file by right-clicking on the ASP.Net theme folder. The Solution
Explorer will then look as follows:
Now add the ASP.Net controls inside the SkinFile.Skin and assign the Style to the controls using
1. A control Id cannot be assigned to ASP.Net controls inside the SkinFile.skin. 2. SkinId must be assigned to the
ASP.Net controls inside the SkinFile.skin. 3. The SkinId should be uniquely defined because duplicate SkinId's per
control type are not allowed
in the same theme. 4. Only one default control skin per control type is allowed in
the same theme.
To use existing ASP.Net Skins in an ASP.Net page we need to assign the existing theme at page level as in the
following.
In the preceding source code, we are assigning the existing ASP.Net Skin File at page level, the existing ASP.Net
Skin automatically appears in the box after using the Themes property in the page header. Assigning the Skin
to the ASP.Net Controls to assign the skin to the ASP.Net controls, you need to assign it to the control's SkinId
Property as in the following:
▪ ASP.NET master pages allow us to create a consistent layout for the pages in our
application.
▪ A single master page defines the look and feel and standard behavior that we want for all of the
pages (or a group of pages) in our application.
▪ We can then create individual content pages that contain the content we want to
display.
▪ When users request the content pages, they merge with the master page to produce output that
combines the layout of the master page with the content from the content page.
▪ Master pages actually consist of two pieces, the master page itself and one or more content
pages.
77 | Salvi College Prof: Sonu Raj |[email protected] | 8080837038 |8976249271
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.
▪ To some extent, a master page looks like a normal ASPX
page.
▪ It contains static HTML such as the <html>, <head>, and <body> elements, and it can also
contain other HTML and ASP.NET server controls.
▪ Inside the master page, you set up the markup that you want to repeat on every page, like the
general structure of the page and the menu.
▪ However, a master page is not a true ASPX page and cannot be requested in the browser directly
it only serves as the template that real web pages called content pages
▪ One difference is that while web forms start with the Page directive, a master page starts with a
Master directive that specifies the same information, as shown here
Q17. Explain relation between content page and master
page
▪ Master page provides a framework (common content as well as the layout) within which the
content from other pages can be displayed.
▪ It provides elements such as headers, footers, style definitions, or navigation bars that are
common to all pages in your web site.
▪ So the Content Pages need not have to duplicate code for shared elements within your Web
site.
▪ It gives a consistent look and feel for all pages in your
application.
▪ The master page layout consists of regions where the content from each content page should be
displayed.
▪ These regions can be set using ContentPlaceHolder server
controls.
▪ These are the regions where you are going to have dynamic content in your
page