Page Event
|
Controls Initialized
|
Is ViewState Enabled
|
When is this Event Raised
|
Logic
|
PreInit |
No | No | After the start stage is complete and before the initialization stage begins | This event can be used
for the following: 1) Check the IsPostBack property. The IsCallback and IsCrossPagePostBack properties are also set at this time. 2) Create or re-create dynamic controls. 3) Set a master page dynamically. 4) Set the Theme property dynamically. 5) Read or set profile property values.
Note: If the request is a postback,
the values of the controls have not yet been restored from view state.
|
Init |
Not guaranteed | No | After all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page. | This event can be used to read or initialize control properties. |
InitComplete |
Not guaranteed | Yes | At the end of the page’s initialization stage. | Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. This event can be used to make changes to view state that you want to make sure are persisted after the next postback. |
LoadViewState |
Not guaranteed | Yes | This event happens only at postbacks | The Viewstate which has been saved in the __VIEWSTATE during the previous
page visit (via the SaveViewState
event) is loaded and then populated into the control hierarchy.
|
LoadPostbackdata |
Not guaranteed | Yes | This event happens only at postbacks | During this event, the posted form data is loaded into the appropriate controls. |
PreLoad |
Yes | Yes | After the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance. | |
Load |
Yes | Yes | The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page. |
The OnLoad event can be used to set control properties and database connections. |
Control events |
Yes | Yes | Raised at the end of the event-handling stage. | These events can be used to handle specific control events, such as a Button control’s Click event or a TextBox control’s TextChanged event.
Note: In a postback request, if the page contains validator
controls, check the IsValid
property of the Page and of individual validation controls before performing
any processing.
|
LoadComplete |
Yes | Yes | Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. | This event can be used for tasks that require that all other controls on the page be loaded. |
PreRender |
Yes | Yes | The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page. |
The event can be used to make final changes to the contents of the page or its controls before the rendering stage begins. |
PreRenderComplete |
Yes | Yes | Raised after each data bound control whose DataSourceID property is set calls its DataBind method. |
|
SaveStateComplete |
Yes | Yes | Raised after view state and control state have been saved for the page and for all controls. |
Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback. |
Render |
Yes | Yes | This is not an event;
instead, at this stage of processing, the Page object calls this method on
each control. All ASP.NET Web server controls have a Render method that
writes out the control’s markup to send to the browser. |
If you create a custom control, you typically override this method to output the control’s markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. We do not need to explicitly render the control in code because a user control automatically incorporates rendering. |
Unload |
Yes | Yes | Raised for each control and then for the page. | This event can be used to do final cleanup for specific controls, such as closing control-specific database connections.
Note: During the
unload stage, the page and its controls have been rendered, so you cannot
make further changes to the response stream. If you attempt to call a method
such as the Response.Write method, the page will throw an
exception.
|
List ASP.NET Page Life Cycle events
Read Only Fields in C#
Read-only
fields allow you to establish a point of data, whose value is not
known at compile time, but that should never change once established.
A read-only field cannot be changed after the initial assignment.
A
readonly field can be given a value only by using an
initializer when it is declared, or by assigning it a
value within a constructor.
A
readonly field can be initialized both at compile time and at
runtime.
- Compile time initialization: Unlike a constant field, a readonly field in not implicitly static.A readonly field can be initialized at class level at the time of its declaration only if it is static and the value is known at compile time.Ex:class MyMathClass{public static readonly double PI = 3.14;}
- Runtime initialization: An instance (non-static) readonly field can only be initialized at runtime. This can be done only within the scope of an instance constructor and nowhere else.Ex:class MyMathClass{public readonly double PI;public MyMathClass (){PI = 3.14;}}If the value of a static read-only field is not known until runtime, you must make use of a static constructor.Ex:class MyMathClass{public static readonly double PI;static MyMathClass(){ PI = 3.14; }}
Static
readonly fields should be initialized in a static constructor
while instance readonly fields should be initialized in instance
constructor(s).
A
readonly field can be static or nonstatic. Unlike const, read-only
fields are not implicitly static.
A
const
field
gets determined at compile time, while a readonly
field
can be determined at runtime.The const keyword
C#
offers the const
keyword to define variables with a fixed, unalterable value (constant
data). Once the value of a constant has been established, it can
never change, and any attempt to alter it results in a compiler
error.
Note:
The declaration and initialization of a constant field must
be simultaneous. This is because of the fact that the
value of constant data must be known at compile time.
Ex:
class
MyMathClass
{
public
const double PI = 3.14;
}
class
Program
{
static
void Main(string[] args)
{
Console.WriteLine("The
value of PI is: {0}", MyMathClass.PI);
}
}
Notice
that the
constant data defined by MyMathClass
is referenced using
a class name prefix (i.e., MyMathClass.PI).
This is due to the fact that constant fields of a class are
implicitly static.
The value assigned to a constant variable must be known at compile time, and therefore a constant member cannot be assigned to an object reference (whose value is computed at runtime). Constant fields are implicitly static. However, it is permissible to define and access a local constant variable within a type member.
The value assigned to a constant variable must be known at compile time, and therefore a constant member cannot be assigned to an object reference (whose value is computed at runtime). Constant fields are implicitly static. However, it is permissible to define and access a local constant variable within a type member.
Ex:
static
void LocalConstStringVariable()
{
//
A local constant data point can be directly accessed.
const
string fixedStr = "Fixed string Data";
Console.WriteLine(fixedStr);
}
Unlike
in C++, in
C# the const keyword cannot be used to qualify parameters or return
values,
and is reserved for the creation of local or instance-level data.
Related
Post:
Read
Only Fields in C#
Explain the data types in C#
- Value Type: Value types, which stores its value directly include all numerical data types (int, float, etc), as well as enumerations and structures, and are allocated on the stack (although if value types are declared as fields within reference types, they will be stored inline on the heap). Value types can be quickly removed from memory once they fall out of the defining scope. When a value type is assigned to another, a member-by-member copy is achieved by default.
- Reference Type: A reference type stores a reference to the value. Reference types are stored in managed heap. If a reference is set to null, then it is not possible to call any non-static member functions or fields against it; doing so would cause an exception to be thrown at runtime.
What are Access Modifiers in C#?
Access
modifiers are keywords used to specify the declared accessibility of
a member or a type. An access specifier precedes the rest of a
members type specification.
Public
– When a member of a class is modified by the public
specifier, that member can be freely accessed by code defined outside
of its class. It marks a member as accessible from an object variable
as well as any derived classes.
Private
– When a member of a class is specified as private, that
member can be accessed only by other members (methods) defined by its
class. In C#, all members are private by default (if no access
specifier is used, a class member is private by default). Enum
and interface are public by default.
Protected
– When a member of a class is specified as protected, that
member is private to their class, but still can be inherited and
accessed by a derived class. Protected methods, however, are not
accessible from an object variable.
Internal
– The internal modifier declares that a member is accessible
throughout all files (by any type) in an assembly, but not outside
the assembly. In simplified terms, a member marked internal is known
throughout a program, but not elsewhere.
The internal modifier can be applied to classes and members of a class, structures and members of structures, interface and enumeration declarations.
Protected
Internal – A member declared protected internal access
is accessible within its own assembly or types derived from the
defining class in the current assembly. The protected internal access
level can be given only to class members.
Destructor
Destructors are used to destruct instances of classes. It can only be used with classes and not with structs. A
class can only have a single destructor, which neither can be called nor inherited or
overloaded. They are invoked automatically as and when determined by the garbage collector. A
destructor cannot have access modifiers or parameters.
The destructor implicitly calls the Object.Finalize method on the object's base class. This means that the Finalize method is called recursively for all of the instances in the inheritance chain, from the most derived to the least derived.
The destructor is called as and when determined by the garbage collector. The garbage collector checks for objects that are no longer being used by the application. These objects are considered eligible for destruction and the GC reclaims their memory. Destructors are also called when the program exits.
Related Post: Constructors
The destructor implicitly calls the Object.Finalize method on the object's base class. This means that the Finalize method is called recursively for all of the instances in the inheritance chain, from the most derived to the least derived.
The destructor is called as and when determined by the garbage collector. The garbage collector checks for objects that are no longer being used by the application. These objects are considered eligible for destruction and the GC reclaims their memory. Destructors are also called when the program exits.
Related Post: Constructors
Constructors
Constructors
(Instance Constructor)
Constructors
are used to create and initialize instances. If the class does not
have a constructor, a default parameterless constructor is
automatically generated and the default values are used to initialize
the object fields (for example, an int is initialized to 0).
When
a class constructor is invoked a new object is created:
Point
myPoint = new Point();
The
class constructor can invoke the constructor of the base class
through the initializer:
public
Cylinder(double radius, double height) : base(radius, height)
{
}
The
class constructor can also invoke another constructor from the
same class by using the keyword this:
public
Point() : this(0,20)
{
}
In
C#, functions are not virtual by default but (aside from
constructors) can be explicitly declared as virtual.
Struct
constructors
Struct
constructors are similar to class constructors, except for the
following differences:
- Structs cannot contain explicit parameterless constructors. Struct members are automatically initialized to their default values.
- A struct cannot have an initializer in the form : base (argument-list).
Static
Constructors
- A given class (or structure) may define only a single static constructor.
- A static constructor executes exactly one time, regardless of how many objects of the type are created.
- A static constructor does not take an access modifier and cannot take any parameters.
- The runtime invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller.
- The static constructor executes before any instance-level constructors.
Related Post: Destructor
Structures in C#
A structure can be thought of as
a lightweight class type having value-based semantics. Typically, structures
are best suited for modelling geometric and mathematical data, and are created
in C# using the struct keyword. A struct type is a
value type that is typically used to encapsulate small groups of related
variables, such as the coordinates of a rectangle or the characteristics of an
item in an inventory. Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types. Structs can implement an interface
but they cannot inherit from another struct. For that reason, struct members
cannot be declared as protected. It is an error to
declare a default (parameterless) constructor for a struct. It is an error to
initialize an instance field in a struct. It is an error to initialize
an instance field in a struct.
A struct cannot inherit from another struct or class, and it cannot be
the base of a class. Structs, however, inherit from the base class Object. Unless you need reference type semantics, a class
that is smaller than 16 bytes may be more efficiently handled by the system as
a struct.
Unlike classes,
structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and
the object cannot be used until all of the fields are initialized.
Explain Classes in detail
A class is the blueprint from which individual objects are created. This blueprint describes the state and behaviour that all the objects of
the class share. A class may be composed of any number of
members (such as properties, methods, and events) and data fields. A class has both an interface and a structure.
Concrete classes
A concrete
class is a class that can be instantiated.
Abstract Classes
Abstract classes are intended to define common behaviours for derived types. An abstract class is designed only as a
parent class from which child classes may be derived. Abstract classes cannot be instantiated. They are often used to
represent abstract concepts
or entities. The incomplete features of the abstract class are then
shared by a group of subclasses which add different variations of the missing
pieces. The behaviours defined by such a class are "generic" and much
of the class will be undefined and unimplemented. Before a class derived from
an abstract class can become concrete, it must implement all of the abstract methods
in parent classes.
Abstract Method
An abstract method
contains no body and is, therefore, not implemented by the base class. Thus, a
derived class must override it. An abstract method is automatically virtual,
and it is an error to use virtual and
abstract together. The abstract
modifier can only be used on normal methods. It cannot be applied to static methods. Properties and indexers
can also be abstract.
When a derived
class inherits an abstract class, it must implement all of the abstract methods
in the base class. If it doesn't then the derived class must also be specified
as abstract. Thus, the abstract attribute is inherited until such time that a
complete implementation is achieved.
Sealed classes
A sealed class
cannot be used as a base class. For this reason, it also cannot be an abstract
class. Sealed classes are primarily used to prevent derivation. They add
another level of strictness during compile-time, improve memory usage, and
trigger certain optimizations that improve run-time efficiency.
Partial classes
The partial keyword
allows the class, struct, method or interface to span across multiple files. Partial classes are classes that can be split over multiple definitions (typically
over multiple files), making it easier to deal with large quantities of code.
At compile time the partial classes are grouped
together, thus logically make no difference to the output. A primary benefit of
partial classes is allowing different programmers to work on different parts of
the same class at the same time. They also make automatically generated code
easier to interpret, as it is separated from other code into a partial class.
Static Classes
When
a class is defined as static, it cannot be instantiated using the new
keyword, and it can contain only static members or fields.
Static classes are sealed and therefore cannot
be inherited. Static classes cannot contain a constructor, although it is still
possible to declare a static constructor to assign initial values or set up
some static state. The System.Console and System.Math classes are good examples of static classes.
Static classes are used to create data and functions that
can be accessed without creating an instance of the class. Static classes can
be used when there is no data or behavior in the class that depends on object
identity.
It is not possible to create instances of a static class
using the new keyword. Static classes are loaded automatically by the .NET
Framework Common Language Runtime (CLR) when the program or namespace
containing the class is loaded
The main features of static classes are:
- They only contain static members.
- They cannot be instantiated.
- They are sealed.
- They cannot contain Instance Constructors.
Static Members
A static method, field, property, or event is callable on
a class even when no instance of the class has been created. If any instances
of the class are created, they cannot be used to access the static member. Only
one copy of static fields and events exists, and static methods and properties
can only access static fields and static events. Static members are initialized before the static member is accessed for the
first time, and before the static constructor, if any is called.
Static methods can be overloaded but not overridden. A
field cannot be declared as static const, a const field
is essentially static in its behavior. It belongs to the type, not to instances
of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static
fields. No object instance is required.
C# does not support static local variables (variables that
are declared in method scope).
Differentiate between an Interface and an Abstract class
Interface:
- Interfaces are closely related to abstract classes that have all members abstract.
- All the methods of an interface must be virtual.
- A Class that implements an interface must provide concrete implementation of all the methods definition in an interface or else must be declared an abstract class.
- In C#, multiple inheritance is possible only through implementation of multiple interfaces.
- An interface defines a contract and can only contains four entities viz methods, properties, events and indexes. An interface thus cannot contain constants, fields, operators, constructors, destructors, static constructors, or types.
- Also an interface cannot contain static members of any kind. The modifiers abstract, public, protected, internal, private, virtual, override is disallowed, as they make no sense in this context.
- Class members that implement the interface members must be publicly accessible.
- Interface increase security by hiding the implementation.
Abstract Class:
- At least one method of an abstract class must be an abstract method that means it may have concrete methods.
- Abstract class’s methods can’t have implementation only when declared abstract, otherwise they can have implementations and they have to be extended.
- Abstract class can implement more than one interfaces, but can inherit only one class.
- Abstract classes can only be derived once.
- Abstract class must override all abstract method and may override virtual methods.
- Abstract class can be used when implementing framework
- Abstract classes are an excellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies.
What is an Interface?
An interface provides a
specification rather than an implementation for its members. The members of
interface will be implemented by the classes and structs that implement the
interface. An interface can contain only methods, properties, events, and
indexers (an abstract class also precisely contains the same members). An
interface is special in the following ways:
- Interface members are all implicitly abstract. In contrast, a class can provide both abstract members and concrete members with implementations.
- A class (or struct) can implement multiple interfaces. In contrast, a class can inherit from only a single class, and a struct cannot inherit at all.
Interface members are always implicitly
public and cannot declare an access modifier. Implementing an interface
means providing a public implementation for all its members:
If a class
that implements an interface does not define all the methods of the interface,
then it must be declared abstract and the method definitions must be provided
by the subclass that extends the abstract class. In addition to this an
interfaces can inherit other interfaces.
interface
ISum
{
int iGetSum(int i, int j); //By Default Public
int iGetSum(int i, int j); //By Default Public
}
class Sum : ISum
{
class Sum : ISum
{
public int iGetSum(int i, int j) //Must be declare Public
{
return i + j;
}
}
State Management in ASP.Net
Web applications are based on stateless HTTP protocol which does not retain any
information about user requests. In typical client and server communication
using HTTP protocol, page is created each time the page is requested.
Various client side state management options in ASP.NET are Cookies, QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0).
Example: This example makes use of cookies to customize web page.
if (Request.Cookies["UId"] != null)
lbMessage.text = "Mr/Mrs" + Request.Cookies["UId"].Value + ", Welcome!";
else
lbMessage.text = "Hi, welcome!";
Client's information can be stored as given below:
View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. Disable View State for all the controls for which you don't need state, to reduce performance penalty (Data grid usually doesn't need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive. View state data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.
string prodId;
Control State is new mechanism in
ASP.NET 2.0 which addresses some of the shortcomings of View State .
Control state can be used to store critical, private information across post
backs. Control state is another type of state container reserved for controls
to maintain their core behavioral functionality whereas View State
only contains state to maintain control's contents (UI). Control
State shares same memory data
structures with View
State . Control State
can be propagated even though the View
State for the control is
disabled.
For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behaviour across post backs. Grid View is in no way affected when we disableView
State for the Grid View
or entire page.
Server Side State Management maintains state information on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.
<sessionState mode = <"inproc" | "sqlserver" | "stateserver">
cookieless = <"true" | "false">
timeout = <positive integer indicating the session timeout in minutes>
sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
server = <The server name that is only required when the mode is State Server>
port = <The port number that is only required when the mode is State Server>
Mode:
This setting supports three options. They are InProc, SQLServer, and State Server.
Cookie less:
This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.
Timeout:
This indicates the Session timeout value in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes.
SqlConnectionString:
This identifies the database connection string that names the database used for mode SQLServer.
Server:
In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.
Port:
This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.
You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.
Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability:
This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server.
Configuration information:
This mode is ideal for scalable and highly available applications. Session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. We can invoke state service using services MMC snap-in or by running following net command from command line.
Net start aspnet_state
Configuration information:
<sessionState mode="StateServer"
StateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=freelance; password=freelance"
cookieless="false" timeout="20"/>
Advantages:
ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.
SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory
C:\<windows>\microsoft.net\framework\<version>. Running this utility will create a database which will manage the session state.
Configuration Information:
2. Supports multiple Web servers: With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client’s state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access).
2. Reduced bandwidth: If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server.
We can classify state management techniques as client side
state management and server side state management, each of which has its own
pros and cons.
Client Side State Management:
Various client side state management options in ASP.NET are Cookies, QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0).
Cookie:
A cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user.
Example: This example makes use of cookies to customize web page.
if (Request.Cookies["UId"] != null)
lbMessage.text = "Mr/Mrs" + Request.Cookies["UId"].Value + ", Welcome!";
else
lbMessage.text = "Hi, welcome!";
Client's information can be stored as given below:
Response.Cookies["UId"].Value=username;
Advantages: - Simplicity
- Cookies can be disabled on user browsers
- Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
- Inappropriate for sensitive data
Hidden fields:
Hidden fields are
not
rendered by the browser and used to store data at the page level. Whenever a page is submitted to server, hidden fields
values are also posted to server along with other controls on the page. We can use hidden fields in ASP.NET pages using following syntax:
protected
System.Web.UI.HtmlControls.HtmlInputHidden HiddenField;
//to
assign a value to Hidden field
HiddenField.Value="This is a hidden field";
//to
retrieve a value
string str=HiddenField.Value;
Advantages: - Simple to implement for a page specific data
- Can store small amount of data so they take less size.
- Inappropriate for sensitive data
- Hidden field values can be intercepted(clearly visible) when passed over a network
View State:
View State is a built in feature in web controls to persist data between page post backs. It can be used to store state information for a single user. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true.
View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. Disable View State for all the controls for which you don't need state, to reduce performance penalty (Data grid usually doesn't need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive. View state data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.
//
Add item to ViewState
ViewState["viewstate"] = viewstateValue;
//Reading
items from ViewState
Response.Write(ViewState["viewstate"]);
Advantages:
Response.Write(ViewState["viewstate"]);
Advantages:
- Simple for page level data
- Encrypted
- Can be set at the control level
- Overhead in encoding View State values
- Makes a page heavy
Query strings:
Query strings are usually used to send information from one page to another page along with URL in clear text. We can only pass smaller amounts of data using query strings. Most browsers impose a limit of 255 characters on URL length. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode. Query strings can be used using the following syntax:string prodId;
prodId=Request.QueryString["prodId"];
Advantages: - Simple to Implement
- Human Readable
- Client browser limit on URL length
- Cross paging functionality makes it redundant
- Easily modified by end user
Control State:
For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behaviour across post backs. Grid View is in no way affected when we disable
Server Side State Management:
Server Side State Management maintains state information on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.
Application State:
Application State is used
to store data which is visible across entire application and shared across
multiple user sessions. Data which needs to be persisted for entire life of
application should be stored in application object.
In classic ASP, application
object is used to store connection strings. It's a great place to store data
which does not changes frequently. We should write to application variable only in Application_Onstart event (global.asax) or Application.Lock event to avoid data
conflicts. Below code sample gives idea:
Application.Lock();
Application["testData"]="testData";
Application.UnLock();
Session State:
Session State is used to
store state specific information per client basis. Session data persists for the duration of user session. Session state can be configured
using the <sessionState> section in the
application's web.config file.
Configuration
information:
<sessionState mode = <"inproc" | "sqlserver" | "stateserver">
cookieless = <"true" | "false">
timeout = <positive integer indicating the session timeout in minutes>
sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
server = <The server name that is only required when the mode is State Server>
port = <The port number that is only required when the mode is State Server>
Mode:
This setting supports three options. They are InProc, SQLServer, and State Server.
Cookie less:
This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.
Timeout:
This indicates the Session timeout value in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes.
SqlConnectionString:
This identifies the database connection string that names the database used for mode SQLServer.
Server:
In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.
Port:
This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.
You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.
Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability:
- In process mode (in-memory) - State information is stored in memory of web server.
- Out-of-process mode - Session state is held in a process called aspnet_state.exe that runs as a windows service.
- Database mode - session state is maintained on a SQL Server database.
This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server.
Configuration information:
<sessionState
mode="Inproc"
sqlConnectionString="data source=server;user
id=freelance;password=freelance"
cookieless="false" timeout="20"
/>
Advantages: - Fastest mode
- Simple configuration
- Session data will be lost if the worker process or application domain recycles
- Not ideal for web gardens and web farms
This mode is ideal for scalable and highly available applications. Session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. We can invoke state service using services MMC snap-in or by running following net command from command line.
Net start aspnet_state
Configuration information:
<sessionState mode="StateServer"
StateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=freelance; password=freelance"
cookieless="false" timeout="20"/>
Advantages:
- Supports web farm and web garden configuration.
- Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state
- Out-of-process mode provides slower access compared to In process.
- Requires serializing data.
ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.
SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory
C:\<windows>\microsoft.net\framework\<version>. Running this utility will create a database which will manage the session state.
Configuration Information:
<sessionState
mode="SQLServer"
sqlConnectionString="data source=server;user
id=freelance;password=freelance"
cookieless="false" timeout="20" />
Advantages: - Supports web farm and web garden configuration
- Session state is persisted across application domain recycles and even IIS restarts when session is maintained on different server.
- Requires serialization of objects
Advantages of Client – Side State Management:
1. Better Scalability: With server-side state management, each client that connects to the Web server consumes memory on the Web server. If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.2. Supports multiple Web servers: With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client’s state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access).
Advantages of Server – Side State Management:
1. Better security: Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, you should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status.
2. Reduced bandwidth: If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server.
Subscribe to:
Posts (Atom)