Interview Questions Part
5 - ASP.NET , Session , Caching
Question 1 :
How to make SQLServer session mode work ?
Answer 1 :
Please do below steps to make SQLServer session mode to work properly :
1. To use SQLServer mode, you must first be sure the ASP.NET session state
database is installed on SQL Server. You can install the ASP.NET session state
database using the Aspnet_regsql.exe tool.
2. To configure an ASP.NET application to use SQLServer mode, do the following
in the application's Web.config file:
•Set the mode attribute of the sessionState element to SQLServer.
•Set the sqlConnectionString attribute to a connection string for your SQL
Server database.
Question 2 :
What is SQL Server session mode in ASP.NET ?
Answer 2 :
SQLServer mode stores session state in a SQL Server database. This ensures that
session state is preserved if the Web application is restarted and also makes
session state available to multiple Web servers in a Web farm.
Question 3 :
How to make State server session mode work ?
Answer 3 :
Please do the below to make State Server session mode work :
1. To use StateServer mode, you must first be sure the ASP.NET state service is
running on the server used for the session store. The ASP.NET state service is
installed as a service when ASP.NET and the .NET Framework are installed. The
ASP.Net state service is installed at the following location:
systemroot\Microsoft.NET\Framework\versionNumber\aspnet_state.exe
2. To configure an ASP.NET application to use StateServer mode, in the application's
Web.config file do the following:
•Set the mode attribute of the sessionState element to StateServer.
•Set the stateConnectionString attribute to tcpip=serverName:42424.
3. To use StateServer mode in a Web farm, you must have the same encryption
keys specified in the machineKey element of your Web configuration for all
applications that are part of the Web farm.
What is StateServer Session mode in ASP.NETIn StateServer mode, session is
stored on seperate computer . It stores session state in a separate process
called the ASP.NET state service. This ensures that session state is preserved
if the Web application is restarted and also makes session state available to
multiple Web servers in a Web farm. This does not support Session_End event in
global.asax
Question 4 :
What are different modes of storing ASP.NET Sessions ?
Answer 4 :
The different modes
ASP.NET sessions are :
- InProc
- StateServer
- SqlServer
Question 5 :
How to make Output Cache maintain seperate cahce entries for each browser ?
Answer 5 :
This is done using below directive :
VaryByCustom="browser"
<%@ OutputCache Duration="60" VaryByParam="None"
VaryByCustom="browser" %>
Question 6 :
What are different types of caching ?
Answer 6 :
Types of caching are :
- Page Output Caching
- Page Fragment Caching
- Data Caching
Question 7 :
Specify various options for Location attribute in OutputCache directive ?
Answer 7 :
If locaction attribute is specified, must be one of: Any, Client,
Downstream, None, Server or ServerAndClient.
Question 8 :
Explain VaryByParam attribute in Output Cache ?
Answer 8 :
VaryByParam attribute is a required attribute in OutputCache directive. The
names of the variables in the Request, which should result in, separate cache
entries. "none" can be used to specify no variation. "*"
can be used to create new cache entries for every different set of variables.
Separate variables with ";".
Question 9 :
What is Cache Callback ?
Answer 9 :
Cache Callback provides an ability where by some actions can be performed when
that item is removed from cache
CacheItemRemovedCallback example
System.Web.Caching.CacheItemRemovedCallback callback = new
System.Web.Caching.CacheItemRemovedCallback (OnRemove);
Cache.Insert("key",myFile,null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
TimeSpan.Zero,
System.Web.Caching.CacheItemPriority.Default, callback);
. . .
public static void OnRemove(string key,
object cacheItem,
System.Web.Caching.CacheItemRemovedReason reason)
{
AppendLog("The cached value with key '" + key +
"' was removed from the cache. Reason: " +
reason.ToString());
}
Question 10:
What are different types of cache dependencies ?
Answer 10:
Different type cache dependencies are :
File dependency
Time Based Expiration
Key dependency
Again in another website:
What
is a Session?
A
Session is a unique instance of the browser. A single user can have multiple
instances of the browser running on his or her machine. If each instance visits
your Web application, each instance has a unique session.A session starts when
a user accesses a page on a Web site for the first time, at which time they are
assigned a unique session ID. The server stores the user's session ID in the
Session.SessionID property.
What is the default session timeout period?
20 minutes.
Where do you generally specify the Session Timeout?
You specify the Session Timeout setting in the web.config file.
Can you specify Session Timeout in a code behind file?
Yes, can specify the Session.Timeout property as shown below in a code behind
file.
Session.Timeout = 10;
How do you end a user session?
You can call the Session.Abandon() method to end a user session. If a user
then tries to access a page the server will assign them a new session ID and it
will clear all the previous session variables. You'll typically use
Session.Abandon() on log-out pages.
What type of data can you store in Application State and Session
State variables?
Application State and Session State variables are used to store data that you
want to keep for the lifetime of an application or for the lifetime of a
session. You can store any type of data in the Application or Session state,
including objects.
Are
Application State or Session State variables type safe?
No,
Application and Session state variables are created on the fly, without
variable name or type checking.
Do maintaining Session state affects performance?
Yes
Can you turn of Session state?
Yes, Session state can be turned off at the application and page
levels.
Are Application state variables available throughout the current
process?
Yes, Application state variables are available throughout the current process,
but not across processes. If an application is scaled to run on multiple
servers or on multiple processors within a server, each process has its own
Application state.
How do you disable Session state for a Web form?
To turn Session state off for a Web form set EnableSessionState property of
the Page to False.
How do you turn Session state off for an entire web application?
In the Web.config file, set the sessionstate tag to False.
What are Application State variables?
Application State variables are global variables that are available from
anywhere in the application. All Sessions can access Application State
variables.
How to add and remove data to Application State Variables?
//Code to add data to Application State
Application.Add("AppName",
"Sample");
//Code to remove data from Application State
Application.Remove("AppName");
How do you remove all Application State Variables data?
//Code to remove all Application State Variables data
Application.RemoveAll();
ASP.NET 3.5 Questions &
Answers :
1.
Explain the life cycle of an ASP .NET page.?
Following are the events occur during ASP.NET Page Life Cycle:
1)Page_PreInit
2)Page_Init
3)Page_InitComplete
4)Page_PreLoad
5)Page_Load
6)Control Events
7)Page_LoadComplete
8)Page_PreRender
9)SaveViewState
10)Page_Render
11)Page_Unload
Among above events Page_Render is the
only event which is raised by page. So we can't write code for this event.
Stage
Description
Page request
The page request occurs before the page life cycle begins. When the page is
requested by a user, ASP.NET determines whether the page needs to be parsed and
compiled (therefore beginning the life of a page), or whether a cached version
of the page can be sent in response without running the page.
Start
In the start stage, page properties such as Request
and Response
are set. At this stage, the page also determines whether the request is a
postback or a new request and sets the IsPostBack
property. The page also sets the UICulture
property.
Initialization
During page initialization, controls on the page are available and each
control's UniqueID
property is set. A master page and themes are also applied to the page if
applicable. If the current request is a postback, the postback data has not yet
been loaded and control property values have not been restored to the values
from view state.
Load
During load, if the current request is a postback, control properties are
loaded with information recovered from view state and control state.
Postback event handling
If the request is a postback, control event handlers are called. After that,
the Validate
method of all validator controls is called, which sets the IsValid
property of individual validator controls and of the page.
Rendering
Before rendering, view state is saved for the page and all controls. During
the rendering stage, the page calls the Render
method for each control, providing a text writer that writes its output to the OutputStream
object of the page's Response
property.
Unload
The Unload
event is raised after the page has been fully rendered, sent to the client, and
is ready to be discarded. At this point, page properties such as Response
and Request
are unloaded and cleanup is performed.
2. how does the cookies work in asp.net?
we know Http is an state-less protocol which is required for interaction
between clinet and server .
so there is an need to remeber state of request raised by an web
browser so that
web server can recognize you have already previously visited or not.
There are two types of state management techniques:
a) Client side state management
b) Server - side statemanagement
Using cookies comes under clinet side statemanagement .In HttpResponse we
write
Cookie containing sessionId and other information within it.
when a browser made a request to the web server the same cookie is
sent to the server where server recognize the session id and get other
information stored to it previously.
3. What is Ispostback method in ASP.Net? Why do we use that??
Basically Post back is an action performed by a interactive Webpage. When it
goes to the server side for a non-client Operation Server again posts it back
to the client and hence the name.
Ex:
if(!IsPostBack)
will not allow the page to post back again n again bcoz it reduces the
performance.
4. Can User Control be stored in library?.
I will say "NO"
there are 3 types of controls:
1) User Control
2) Custom Control
3) Web parts
you can reuse User control in the current project in which you have built it,
but you can't move it to other project as unless you just copy paste the same
file there and make the changes for that project ( which violets the concept of
library).
but custom control can be shared between projects. and you can precompile them
even as a dll, so this means you can use them in library of any type.
5. what is the difference between application state and caching?
Application Object and Cached Object both falls under Server side State
Management.
Application object resides in InProc i.e. on the same server where we
hosted our application.
Cache Object resides on server side/ DownStream/Client Side.
Application Object will be disposed once application will stop.
Cache Object can be disposed using Time based cache dependency.
Only one user can access Application Object at a time hence we have
to lock it every time we modify it.
6. what is boxing and unboxing?
Boxing is what happens when a value-type object is assigned to
a reference-type variable.
Unboxing is what happens when a reference-type variable is
assigned to a value-type variable.
7. What are the uses of Reflection??
Reflection is a concept using which we can
1) Load assemblies dynamically
2) Invoke methods at runtime
3) Retriving type information at runtime.
8. What is the use of AutoWireup in asp.net?
AutoEventWireup attribute is used to set whether the events needs to
be automatically generated or not.
In the case where AutoEventWireup attribute is set to false (by default) event
handlers are automatically required for Page_Load or Page_Init. However when we
set the value of the AutoEventWireup attribute to true the ASP.NET runtime does
not require events to specify event handlers like Page_Load or
Page_Init.
9. what events will occur when a page is loaded?
Below are the events occures during page load.
1) Page_PreInit
2) Page_Init
3) Page_InitComplete
4) Page_PreLoad
10. Where is the View state Data stored?
ViewState data is stored in the hidden field. When the page is submitted to the
server the data is sent to the server in the form of hidden fields for each
control. If th viewstate of the control is enable true the value is retained on
the post back to the client when the page is post backed.
11. What is the difference between custom web user control and a custom
web server control?
Web User Control:
1) Easy to Create.
2) It Can be used inside the same Application.(To use it in other application
we need to add it to that project.)
3) It Can take advantage of Caching Technique.
Web Server Control:
1) Bit tuff to create as compare to User Control.
2) Easy to use.
3) Can be added to ToolBox.
12. Where do the Cookie State and Session State information be stored?
Cookie Information will be stored in a txt file on client system under a
folder named Cookies. Search for it in your system you will find it.
Coming to
Session State
As we know for every process some default space will be allocated by OS.
In case of InProc Session Info will be stored
inside the process where our
application is running.
In case of StateServer Session Info will be stored using ASP.NET State Service.
In case of SQLServer Session info will be stored inside Database. Default
DB
which will be created after running InstallSQLState Script is ASPState.
13. What is the difference between adding
reference in solution Explorer and adding references by USING ?
Adding reference in solution explorer is used to add the DLL for that
project for reference only. If you want to utilize that DLL methods/functions
in our aspx.cs/.cs file etc you must write using that nameclass library name in
file.
14. What are the different types of sessions in ASP.Net? Name them.?
Session Management can be achieved in two ways
1)InProc
2)OutProc
OutProc is again two types
1)State Server
2)SQL Server
InProc
Adv.:
1) Faster as session resides in the same process as the application
2) No need to serialize the data
DisAdv.:
1) Will degrade the performance of the application if large chunk of data is
stored
2) On restart of IIS all the Session info will be lost
State Server
Adv.:
1) Faster then SQL Server session management
2) Safer then InProc. As IIS restart
won't effect the session data
DisAdv.:
1) Data need to be serialized
2) On restart of ASP.NET State Service session info will be lost
3)Slower as compared to InProc
SQL Server
Adv.:
1) Reliable and Durable
2) IIS and ASP.NET State Service
restart won't effect the session data
3) Good place for storing large chunk of data
DisAdv.:
1) Data need to be serialized
2) Slower as compare to InProc and State Server
3)Need to purchase Licensed
version of SQL Serve
15. How do you design a website with multilingual support in ASP.NET?
Multilingual website can be created using Globalization and Localization.
Using Globalization we change the Currency Date
Numbers etc to Language Specific Format.
To change the string which is there in the label
button etc to language specific string we use Localization.
In Localization we have to create different
Resource files for different languages.
During this process we use some classes present in System.Resources
System.Globalization System.Threading namespaces.
16. What is caching? What are different ways of caching in ASP.NET?
Caching is a technique of persisting the data in memory for immediate
access to requesting program calls. This is considered as the best way to
enhance the performance of the application.
Caching is of 3 types:
Output Caching - Caches the whole page.
Fragment Caching - Caches a part of the page
Data Caching - Caches the data
17. What is meant by 3-tier architecture.
We generally split our application into 3-Layers
1)Presentation Layer ( Where we keep all web forms
Master Pages and User Controls).
2)Business Layer (Where we keep business logic). e.g
Code related to manipulating data Custom Exception classes Custom Control
classes Login related code if any etc. etc.
3)Data Access Layer (Where we keep code used to
interact with DB). e.g. We can have the methods which are using SQL Helper
(Application Block).
18. Explain the basic functionality of
garbage collector?
Garbage Collector in .Net Framework is used for Automatic Memory Management
i.e. it is collect all unused memory area and give to application.
system.gc.collect() is a method for release the memory. But remember one think
it is only an request i.e. we can't explicitly release the memory by using
system.gc.collect().
19. What is the difference between mechine.config
and web.config?
machine.config is a system level configuration i.e it is applied on
all application in o/s that the configuration is set where as in
web.config it is applicable to only one application i.e each
asp.net webapplication will contain atleast on web.config file.
20. How can exception be handled with out
the use of try catch?
using Exception Management application block
or
Page_error
Application_error objects
21. What is the difference between
Response.Redirect and Server.Transfer.
Server.Transfer transfers page processing from one page
directly to the next page without making a round-trip back to the client's
browser. This provides a faster response with a little less overhead
on the server.Server.Transfer does not update the clients url history
list or current url.
Response.Redirect is used toredirect the user's browser to another
page or site. This performs a trip back to the client where the client's
browser is redirected to the new page. The user's browser history list is
updated to reflect the new address.
22. Where the assembly is stored in
asp.net?.
private are stored in application / bin directory and public
are stored in GAC.
23. How we implement Web farm and Web
Garden concept in ASP.NET?.
A web farm is a multi-server scenario. So we may have a server in each state of
US. If the load on one server is in excess then the other servers step in to
bear the brunt.
How they bear it is based on various models.
1. RoundRobin. (All servers share load equally)
2. NLB (economical)
3. HLB (expensive but can scale up to 8192 servers)
4. Hybrid (of 2 and 3).
5. CLB (Component load balancer).
A web garden is a multi-processor setup. i.e. a single server (not like the
multi server above).
How to implement webfarms in .Net:
Go to web.config and
Here for mode you have 4 options.
a) Say mode inproc (non web farm but fast when you have very few customers).
b) Say mode StateServer (for webfarm)
c) Say mode SqlServer (for webfarm)
Whether to use option b or c depends on situation. StateServer is faster but
SqlServer is more reliable and used for mission critical applications.
How to use webgardens in .Net:
Go to web.config and
Change the false to true. You have one more attribute that is related to
webgarden in the same tag called cpuMask.
24. Is there any limit for query string?
means what is the maximum size?..
Servers should be cautious about depending on URI lengths above 255 bytes
because some older client or proxy implementations may not properly support
these lengths.
Query string length depends on browser
compatability
IE supports upto 255
Firefox supports upto 4000
25. What is the exact purpose of http
handlers?
ASP.NET maps HTTP requests to HttpHandlers. Each HttpHandler enables processing
of individual HTTP URLs or groups of URL extensions within an application.
HttpHandlers have the same functionality as ISAPI extensions with a much
simpler programming model
Ex
1.Default HttpHandler for all ASP.NET pages ->ASP.NET Page Handler (*.aspx)
2.Default HttpHandler for all ASP.NET service pages->ASP.NET Service Handler
(*.asmx)
An HttpHandler can be either synchronous or
asynchronous. A synchronous handler does not return until it finishes
processing the HTTP request for which it is called. An asynchronous handler
usually launches a process that can be lengthy and returns before that process
finishes
After writing and compiling the code to implement an HttpHandler you must
register the handler using your application's Web.config file.
In Code Project Website:
There are a lot of articles available on different ways of managing the states in the web. I was not able to find details
on Application Object and events. So I read different books and articles
and thought of sharing my knowledge with all of you. Hope you will like it and
give your feedback and suggestions.
As we all know, web is stateless
.
A Web page is recreated every time it is posted back to the server. In
traditional web programming, all the information within the page and control
gets wiped off on every postback. To overcome this problem, ASP.NET Framework provides various ways to
preserve the states at various stages like
controlstate, viewstate, cookies, session, etc. These can be
defined in client side and server side state
management. Please see the image below:
Figure:
Options available to maintain the state
There are lot more written about most of them. In this article, I am going
to explore mainly Application
state, Application events and Application
Objects.
First, I am going to explain ASP.NET Application Lifecycle. One needs to really
understand the application Lifecycle, so
that one can code efficiently and use the resources available. Also it is very
important to discuss, as we are going to Application
level events, objects, etc.
ASP.NET uses lazy initialization
technique for creating the application
domains, i.e., Application domain for an application is created only when the first
request is received by the web server. We can categorise Application life cycle in several stages. These
can be:
- Stage 1: User first
requests any resource from the webserver.
- Stage 2: Application receives very first request from
the application.
- Stage 3: Application basic Objects are created.
- Stage 4: An
HTTP
application
object is assigned to the
request.
- Stage 5: And the
request is processed by the
HTTP
Application
pipeline.
I'll explain the points one by one.
Stage 1: The Application
life cycle starts when a user hits the URL by typing it in the browser. The
browser sends this request to the webserver. When webserver receives the
request from the browser, it examines the file extension of the requested file
and checks which ISAPI extension
is
required to handle this request and then passes the request to the appropriate
ISAPI extension.
Figure:
URL Processing
Note 1: If any extension is not mapped to any ISAPI
extension, then ASP.NET will not receive
the request and the request is handled by the server itself and ASP.NET authentication, etc. will not be applied.
Note 2: We can also make our own custom handler,
to process any specific file extension.
Stage 2: When ASP.NET
receives the first request, the Application
manager creates an application
domain for it. Application domains
are very important because they provide the isolation amongst
various applications on the webserver and
every application domain is loaded and
unloaded separately, and in application
domain an instance of class HostingEnvironment
is created which provides access to information about all application resources.
Figure:
ASP.NET Handling first request
Stage 3: After creating the application domain and hosting environment, ASP.NET initializes the basic objects as HTTPContext
,
HTTPRequest
and HTTPResponse
.
HTTPContext
holds objects
to the specific application request as HTTPRequest
and HTTPResponse
.HTTPRequest
contains all the information regarding the current request like cookies,
browser information, etc. and HTTPResponse
contains the response that is sent to client.
Stage 4: Here all the basic objects are being
initialized and the application is being
started with the creation of HTTP
Application class, if there is Global.asax (It
is derived from HTTP
Application
class)
in the application, then that is
instantiated.
Figure:
Multiple requests processed by ASP.NET
Note: When the application
is accessed for the first time, the HTTP
Application instance is created for further
requests. It may be used for other requests as well.
Stage 5: There are a lot of events executed by the HTTP
Application
class.
Here, I have listed down a few important ones. These events can be used for any specific requirement.
To handle application events or methods, we can have a file named Global.asax
in the root directory of your application.
At any single point of time, an HTTP
Application
instance
handles only one request, so we don't need to think about locking and unlocking
of any non static
members, but
for static
members we do
require. I'll discuss it in detail in a later section of this article.
Following are the commonly used events in
the global.asax file.
Figure:
Methods in Global.asax
If we are going to change the source code, then ASP.NET requires to recompile into assemblies and
also the application will restart as well.
In spite of this, there are also certain things that force the application to get restarted. If we'll change in
the following folder whether adding, modifying or deleting, the application will restart:
- Any changes
in the application's bin
folder
- Changes in
Localisation resources, i.e.,
App_GlobalResources
or App_LocalResources
folders
·
Changes in Global.asax file
·
Modification of any source code in App_code
folder
- Any changes
in web.config file
- Any changes
in the webservice references, i.e.,
App_WebReferences
folder.
Application state is one of the ways available to store some
data on the server and faster than accessing the database.The data stored on
the Application state is available to all the users(Sessions)
accessing the application. So application state
is very useful to store small data that is used across the application and same for all the users. Also we
can say they are global variables available across the users. As I am saying
small data, we should not store heavy data in ApplicationState
because it is stored on the server and can cause performance
overhead if it is heavy. We'll discuss it later. Technically the data is shared
amongst users via HTTPApplcation
State class and the data can be stored here in key
value pair
. It can also be accessed through Application
property
of the HTTPContext
class.
As I have already discussed above, an instance of Http
ApplicationState is created when first time a
request comes from any user to access any resource from the application. And this can be accessed through the
property Application
property of HTTPContext
Object.
All HTTPModules
and Handlers
have access to this property. The lifetime of the values spans through the
lifetime of the ASP.NET application until the application is unloaded. Normally, we set these Application
variables
in Application_OnStart
event in Global.asax file and access and modify through ASP.NET pages.
One thing to keep in mind is that application
state stores the data as of Object
type, so at the time of reading, the values we need to convert it in the
appropriate type.
So normally, we use to store the Application
wise data in Application state which is shared across the users. So we can
save the data in Application_OnStart
method in Global.asax file as:
Collapse
void Application_Start(object sender, EventArgs e)
{
Application["Message"] = "Welcome to my Website";
}
We can also save object of some Class in Application
variable. Let's say we have a class as:
Collapse
public class Employee
{
private string _name;
public string Name {
get
{
return _name;
}
set
{
_name = value;
}
}
private decimal _annualSalary;
public decimal AnnualSalary
{
get
{
return _annualSalary;
}
set
{
_annualSalary = value;
}
}
public Employee()
{
}
}
Put this class file in App_Code folder. Now class will be available
throughout the application so also in Global.asax.
Now to save it in Application_OnStart
as:
Collapse
void Application_Start(object sender, EventArgs e)
{
Employee objEmployee = new Employee();
objEmployee.Name = "Brij";
objEmployee.AnnualSalary = 1000000;
Application["EmployeeObject"] = objEmployee;
}
Note: Here one thing I would like to mention is that we
don't require to serialize the object to store in Application
state as we need to keep in mind in case of
viewstate, etc. So there is no need of serialization
here. :) We can also modify these values from any method in the application. Here I am modifying Application["Message"]
in onclick
method of a button
in a page as:
Collapse
protected void Button1_Click(object sender, EventArgs e)
{
Application["Message"] = "Welcome Dude!!";
}
Now we'll get the modified values whenever we try to access it. Let's also
add a new variable on another button Click event as:
Collapse
protected void Button3_Click(object sender, EventArgs e)
{
Application["NewValue"] = "Hello";
}
This value will also be available throughout the application life. One thing I also want to
discuss is that Application state is not
thread safe
so it can be accessed by multiple threads at the same
time, i.e., if we have stored some value in Application
state say some counter and we increase it
whenever a particular page is accessed. So at a single point of time, two
instances of page of a different session can read the same value and update it.
So we'll not get the desired result. So here we need some synchronisation
mechanism so that at a single point of time only, one can update its value.
Here we can call the System.Web.Http
ApplicationState.Lock
method, set the application state value, and then call the System.Web.Http
ApplicationState.UnLock
method to unlock the application state, freeing it for other write or update it
as:
Collapse
if (Application["Counter"] != null)
{
Application.Lock();
Application["Counter"] = ((int)Application["Counter"]) + 1;
Application.UnLock();
}
So by this way, we can avoid writing the same value from multiple Threads at
the same time.
So to read from Application state is fairly simple. We should just have a
safety check to see whether the value we are accessing is null
,
if the data will not be in Application state is not there then it will return null
and if we'll try to cast it in any different type, it'll throw an
exception. As I already discussed, Application
state stores the data in object form so we
need to typecast after reading it. So we can read the value as:
Collapse
if(Application["Message"] !=null)
{
string message = Application["Message"] as string;
}
The object also can be read as:
Collapse
if (Application["EmployeeObject"] != null)
{
Employee myObj = Application["EmployeeObject"] as Employee;
string Name = myObj.Name;
}
A classic example of Application
variable can be to show the number of online user in a website. This can be
done in the following steps:
- Add an
online counter variable Application
Start
method
of Global.asax file as:
Collapse
Application["OnlineCounter"] = 0;
So in this, a variable will be added when the application first starts and will be initialized
to 0
as there will be no
logged in user at that point of time.
- Now as we
know whenever a new user opens the website, a new session is created and
Session_Start
method
of Global.asax is called. So we can increase the counter in this
method as:
Collapse
void Session_Start(object sender, EventArgs e)
{
if (Application["OnlineCounter"] != null)
{
Application.Lock();
Application["OnlineCounter"] =
((int)Application["OnlineCounter"]) + 1;
Application.UnLock();
}
}
We should use the Locks, else we may get the wrong
result because this may be updated at the same time and updated data is not
correct. How: Let's say we currently have Application["OnlineCounter"]
is 5
and at the same
time, two sessions read the value 5
and
make an increment to 6
and updated it. Application state
as 6. So although two users are logged in, the counter is increased by one
only. So to avoid this, we should use the locks.
- So also at
the time session ends, we should decrease it by one. As I already
discussed, an event
Session_End
is fired
whenever a session ends. So it can be done as:
Collapse
void Session_End(object sender, EventArgs e)
{
if (Application["OnlineCounter"] != null)
{
Application.Lock();
Application["OnlineCounter"] =
((int)Application["OnlineCounter"]) - 1;
Application.UnLock();
}
}
- And this
value can be accessed throughout the application
at any point of time in the application
as:
Collapse
if (Application["OnlineCounter"] != null)
{
int OnlineUsers = ((int)Application["OnlineCounter"]);
}
and this value can be used anywhere in the application.
Application State:
Points to Think About Before Using
- Application state is stored in memory of webserver, so
huge amount of data can cause severe performance overhead. Also keep in
mind that these variables will be stored in memory till the application ends whether we need the entire
time or not. So use it judiciously.
- If the application goes down or is restarted, then
all the data stored in Application state is lost.
- Also Application data is not shared between
multiple servers in webfarm scenario.
- Application also
doesn't work in case of Webgarden. Variables stored in application state
in either of those scenarios are global only to the particular process in
which the application is running. Each
application process can have different
values.
- Application state is not thread safe, so we must keep
the synchronisation in mind as discussed above.
Although both provide the same feature and can be used to store the data at application level, there are a lot of differences
between both.
Sr No
|
Application
State
|
Cache
|
1
|
Application
variables are one of the techniques provided by ASP/ASP.NET to store the data at application level and this is available to all
users.
|
Cache is one technique provided by ASP.NET to store the data at the application level with many options.
|
2
|
Application
variables are available throughout the lifecycle of the application until explicitly removed or
overridden.
|
Cache is volatile. It provides the opportunity to
automatically expire the data based on the settings or memory gets reclaimed
when memory is scarce.
|
3
|
Application
variable should be used only when data is limited, i.e., it should not be
like we store some dataset and keep adding the data in same, which may lead
to choke the webserver
|
Cache provides a flexible way to store data on the
webserver and also get removed when memory becomes low.
|
Cookies
A cookie is a small file which is stored in the visitor's hard disk drive.
This is helpful for storing small and trivial information. According to the RFC [^]
, a cookie can have a maximum size of 4KB. The web server creates a cookie,
attaches an additional HTTP header to the response, and sends it to the
browser. The browser will then create this cookie in a visitor's computer and
includes this cookie for all further requests made to the same domain. Servers
can read the cookie value from the request and retain the state.
The server adds the following to the HTTP header for creating a cookie
Set-Cookie: key=value
The browser reads the above value and creates cookies at the user's end. It
adds the cookie value to the request like
Cookie: key=value
Note: The location where the cookie is stored is completly
controlled by the browser. Sometimes it may keep the cookie in its memory instead
of creating a file.
Creating and using a cookie is trivial in ASP.NET.
The HttpCookie
class is a
key/value collection which allows storing string values. The following code
shows how to create a cookie and send it to the client. Cookies are added using
Response
property and
retrieved using Request
.
Response.Cookies["id"].Value = "10";
Since no expiry time specified, a cookie added like the above method will be
cleared by the browser immediately when it is closed. If you would like to keep
the cookie for a long time, you have to use the HttpCookie.Expires
property set with an expiration date.
The following code shows how to do that.
Response.Cookies["id"].Value = "10";
Response.Cookies["id"].Expires = DateTime.Now.AddDays(1);
Once you set the cookie, the browser will include it for every request. You
read the cookie from the Request.Cookies
collection by specifying cookie name. Consider the following code
if (Request.Cookies["id"] != null) {
string userId = Request.Cookies["id"].Value;
Response.Write("User Id value" + userId);
}
Cookies are managed by the browser and will take care about removing expired
cookies. If you need to remove a cookie before the expiry period, you have to
create a cookie with the same name and with an expiry date that is already
passed. This will make browser think that the cookie is expired and will be
removed immediately. Here is how you do that
Response.Cookies["id"].Expires = DateTime.Now.AddDays(-1);
Some Useful Properties you Must
Know Before Using Cookies
Property name
|
Description
|
Domain
|
Specifies which domain is associated with this cookie.
Default is the current domain. See security constraints later in this article
|
Expires
|
A DateTime value specifies the
expiry time of the cookie
|
HttpOnly
|
Cookies can be accessed using java script. Setting this
property prevents cookies being accessed from java script
|
Secure
|
Set this if cookies are transmitted over SSL
|
Name
|
Cookie name
|
Value
|
Cookie value (string)
|
Multi-valued Cookies
RFC states that a browser should not
store more than 20 cookies from a domain. Multi-Valued cookie is very handy
when you have more items to keep in cookie. To create a multi-valued cookie,
you instantiate the HttpCookie
instance and set it's values. Consider the following code
HttpCookie cookie = new HttpCookie("user");
cookie["name"] = "Foo";
cookie["age"] = "22";
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
Here is how you read it
HttpCookie cookie = Request.Cookies["user"];
if (cookie != null) {
string name = cookie["name"];
string age = cookie["age"];
}
else
A Practical Example
You might have noticed the "Remember me next" time option in most
of the websites. This is done using cookies. The following steps will be
involved when you choose this option.
- When the
user checks the "Remember me next time" option, create a cookie
with a value to identify the user (eg: user id).
- When the
page loads, check for cookie existence. If it exists, read the cookie
value.
- Authenticate
the value and create a session.
Security Constraints
Since cookies are stored in the visitors computer, to prevent it from
harming the system, browsers ensure some security constrains to cookies. THe
following points explain the security constraints:
- Cookies
are specific to domains, which mean that a cookie set from
"DomainA" is not accessible to "DomainB". Browsers
store the domain with each cookie and will ensure it won't be sent to
another domain.
- Other
restriction is in size. Browsers will not allow storing cookies for more
than 4KB from a domain.
- Browsers
provides the option to disable cookies
Proper design of the application can
avoid malicious attacks through cookies. Consider a website which sets the
current user id in a cookie for retaining the user account information in
subsequent visits. Since the cookie is kept in the visitor's system as plain
text, the user can always goto the folder where the cookie is kept and change
the user id to some other value. When the website is requested again, it will
use the new user id which will give the hacker access to the new account.
While cookies are mostly used for storing account information, they are
really not intended for such use. You should always take precautions to avoid
hacks like the above by encrypting the values before keeping in cookie.
Pros and Cons
A cookie is a very handy and easily usable state
management technique. It is useful when you
want to keep small information that is needed for long periods of time. The
processing overhead of cookies is much less compared to sessions. However, it
has the following disadvantages:
- Cookies
have a size limitation of 4KB. Storing huge information is not possible.
- Cookies
can be easily tampered as they are kept in the client's machine. So
additional security checking has to be done when using them.
- The user
can disable cookies.
Session State
A cookie is very simple and is not suitable for sophisticated storage
requirements. Session state is a workaround
for this problem and it gives a method to keep more complex objects securely. ASP.NET allows programmers to keep any type of
objects in session. 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.
The following code shows storing a string value in session.
Session["name"] = "Navaneeth";
Session accepts a System.
Object
type. So you need a type cast when reading. Reading values from session is like
string name = Session["name"] as string;
if(!string.IsNullOrEmpty(name))
Values stored in sessions can be removed by several methods. The following
table shows different methods used.
Method
|
Description
|
Session.Abandon()
|
Cancels the session and fires end
event. This is used when you are done with the session.
|
Session.Clear() / Session.RemoveAll()
|
Clears all contents of the session. This will not end the
session
|
Session.Remove(string)
|
Removes the session name supplied.
|
How Session Works?
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. The following code shows how to get the session id
string sessionId = Session.SessionID;
If you haven't stored anything in the session, ASP.NET
will generate a different session id for each request. Once a session has
contents, the session id will not change. Session id is the only information
which is sent to the client about sessions. As said before, ASP.NET sends session id in a cookie named ASP.NET_SessionId
. But this will not work if
cookies are disabled by the visitor. In such cases, ASP.NET passes session id through the URL. This
behaviour can be controlled by adding the following section to web.config
file under the system.web
section.
<sessionState
cookieless="UseUri" />
Note: ASP.NET AJAX
extensions won't work as expected if this is enabled.
Session Timeout
Each session will have a timeout value (default 20Mins). If the page is not
getting any requests within the timeout limit specified, ASP.NET will assume that the user has left the application and it immediately terminates the
session and fires the End
event. This helps the server to cleanup unused sessions and gives room for new
requests. Timeout value can be changed from web.config
file or through code. Timeout value is specified in minutes.
<sessionState
timeout="60" />
or
Session.Timeout = 60;
Session Timing out Frequently
I have seen many questions on discussion forums which state, "My session timeout is 60 minutes and
it is timing out before that." Well, ASP.NET
will clear session when any of the following happens
- ASP.NET worker process recycles frequently.
When this happens, it will clear all active sessions.
- When
files like
web.config
or application
assemblies are modified, ASP.NET will
recyle the worker process.
Where Session is Stored?
ASP.NET allows three types of session
storage which are described below
Mode
|
Configuration
|
Storage location
|
Description
|
Pros/Cons
|
InProc
|
<session State mode= "InProc" / >
|
ASP.NET processes
memory area
|
This is the default session storage. Session data will be
kept in the server memory. InProc mode is a high
performant as it reads from the same processes memory and it allows you to
keep all .NET types. If session mode is not specified, ASP.NET will use InProc
as the default mode.
|
As the InProc mode keeps data in
same processes memory area, any impacts happened for the ASP.NET worker process will affect the session
data.
|
StateServer
|
<session State
mode= "StateServer"
stateConnectionString= "tcpip=Yourservername:42424" / >
|
Server memory as a seprate process
|
StateServer
mode provides a basic level of isolation for the data storage. It runs as a
separate windows service and keeps the session data out of ASP.NET process memory area. To access session,
ASP.NET process has to communicate with
this external process.
|
It is less performant compared to InProc
mode. But this helps you to avoid loosing session data when ASP.NET worker process restarts.
|
SQL Server
|
<session State mode= "SQLServer"
sqlConnectionString= "..." / >
|
In SQL server database
|
If you still need more resillient storage, SQLServer mode
is the choice. It allows to keep session data in SQLServer. This is helpful
when your web application is hosted in a
webfarm.
|
- Slow
data access
- Allows
to store only serializable types
|
If any of the above discussed methods are not satisfying your storage
requirements, ASP.NET allows to specify a
custom storage provider. This [^] article shows how to do this.
Usage and Best Practices
Incorrect usage of session will blow up your application.
The most common error users make is the NULL reference exceptions when using
sessions. Consider the following code
string name = Session["name"].ToString();
This code is problematic as session[
"name"]
may not exist or may be NULL
and ToString()
will be called on that NULL
reference which will throw the
common "Object reference not set to an instance of the object" error.
Another problem with session is that it is not strongly typed. Session keeps
System.
Object
type which means every .NET type can be kept in session. Consider the following
code
Session["age"] = "I can store a value that is not number!";
Since it is not strongly typed, Session[
"age"]
can contain any value and you will
have problems when using this. Also, you may make typing mistakes when typing
the session names. This will also lead to unexpected behaviours. The following
section describes workarounds for these problems.
Wrapping Session in a Strongly Typed
Class
To workaround the above problems, we can create a strongly typed wrapper
classes around the session and route all calls to session through this wrapper.
Consider a simple scenario where you need to keep user details like name, age,
email validated etc in a session. We create a class to represent all required
fields. See the following code
public class PersonSession
{
const string KEY = "personDetails";
public PersonSession(int id,string name,int age,bool emailValidated)
{
this.Id = id;
this.Name = name;
this.Age = age;
this.HasEmailValidated = emailValidated;
}
public static PersonSession GetPersonSession() {
return HttpContext.Current.Session[KEY] as PersonSession;
}
public static void CreatePersonSession(PersonSession person) {
HttpContext.Current.Session[KEY] = person;
}
public int Id { get; private set; }
public string Name { get; private set; }
public int Age { get; private set; }
public bool HasEmailValidated { get; private set; }
}
The above given class abstracts the session access and provides a clear
interface to access the session contents safely. The static methods CreatePersonSession
and GetPersonSession
can be used to create
and get details of a person from session. The following code shows how to store
person details into session.
PersonSession person = new PersonSession(int.Parse(txtPersonId.Text),
txtName.Text, int.Parse(txtAge.Text), chkEmailValidated.Checked);
PersonSession.CreatePersonSession(person);
To retrieve person details, you need to do
PersonSession person = PersonSession.GetPersonSession();
if (person != null) {
}
Note: HttpContext.Current.Session
is needed when accessing from a class that is not derived from System.Web.UI.Page
.
Base Page Class Approach
Assume that you need to prevent users from seeing your page unless person
details exists in session. You may end up doing the following code for all the
pages that needs to be secured.
protected void Page_Load(object sender, EventArgs e)
{
PersonSession person = PersonSession.GetPersonSession();
if (person == null) {
}
}
Writing the above code in all pages that needs session is redundant. It is
very tough to make a change if something got changed in the session wrapper
class-PersonSession. The recommended approach is to keep a base page class
which is derived from System.Web.UI.Page
and all your pages which need PersonSession
should inherit from this base page class. This allows you to do the session
checking in the base class and redirect the user if required. The following diagram
shows this approach.
We create two classes NormalPage
and SecuredPage
both derived
from System.Web.UI.Page
. SecuredPage
overrides the OnInit
method which looks like this:
protected override void OnInit(EventArgs e) {
base.OnInit(e);
PersonSession person = PersonSession.GetPersonSession();
if (person == null) {
Response.Redirect("NotLogged.aspx");
}
else
this.Person = person;
}
If person details are not found in the session, it redirects to the NotLogged.aspx
page and it sets the Person
property if session exists.
Classes which derive from this class can use this Person
property to access the person details. Usage of
this class is pretty straightforward. See the following code.
public partial class AuthenticatedPage : SecuredPage
{
protected void Page_Load(object sender, EventArgs e)
{
lblMessage.Text = "Session exist";
lblMessage.Text += string.Format("Person Id : {0}",Person.Id);
lblMessage.Text += string.Format("Person Name : {0}", Person.Name);
lblMessage.Text += string.Format("Person Age : {0}", Person.Age);
lblMessage.Text += string.Format("Email validated? : {0}", Person.HasEmailValidated);
}
}
Note: We are not using NormalPage
here. If you have any particular behaviour common for all non-authenticated
pages, this class is the best place to add that.
That's all about sessions. When using it, try not to abuse sessions.
Overusing sessions may degrade your application
performance.
Application
State
ASP.NET implements application state
using the System.Web.Http
ApplicationState
class. It provides methods for storing information which can be accessed
globally. Information stored on application
state will be available for all the users
using the website. Usage of application state is the same as sessions. The following code
shows storing a value in an application
variable and reading from it.
Application["pageTitle"] = "Welcome to my website - ";
application
string pageTitle;
if (Application["pageTitle"] != null)
pageTitle = Application["pageTitle"].ToString();
Understanding Session and Application Events
Before we discuss the practical usage of application
state, you should get a basic knowledge
about the events associated with application
and session. These events can be seen in the global.asax file. See the
following table for the details.
Event name
|
Description
|
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 mod.
|
A Practical Example
The most common usage of application
variables is to count the active number of visitors that are browsing
currently. We can utilize session_start
and session_end
events to do
this. The following code shows how this is done.
void Application_Start(object sender, EventArgs e)
{
Application
Application["activeVisitors"] = 0;
}
void Session_Start(object sender, EventArgs e)
{
if (Application["activeVisitors"] != null) {
Application.Lock();
int visitorCount = (int)Application["activeVisitors"];
Application["activeVisitors"] = visitorCount++;
Application.UnLock();
}
}
You might have noticed Application.Lock()
and Application.UnLock()
calls. ASP.NET is multithreaded and this is required to
synchronize data when multiple visitors access the site at the same time.
Application state is not providing any timeout method like
session. Application state will be available until the application ends. So one should be very careful
when using application state. You should explicitly cleanup the values
stored when you are finished using it.
Keeping State
in Static (shared in VB) Variables
Static variables will have a lifetime until the application domain where it is hosted ends. ASP.NET hosts each website in a separate application domain to provide isolation with
other websites hosted on the same server.
Consider you have a page where all product details are displayed. Product
details are fetched from the database and filled into custom collection and
returned back to the page. To avoid fetching product details all time for each
visitors, we can load it when it is requested for the first time and keep it in
a static variable to serve for the next requests. Consider the following Product
and ProductServices
class.
class Product
{
public Product(int id,string name) {
this.Id = id;
this.Name = name;
}
public int Id { get; private set; }
public string Name { get; private set; }
}
class ProductService
{
static List<Product> products = null;
static readonly object locker = new object();
public static List<Product> GetAllProducts() {
if (products != null) {
lock (locker) {
if (products != null) {
}
}
}
return products;
}
}
The above given code is self explanatory. The variable products
will have a lifetime until the application domain unloads. When ProductService.GetAllProducts()
is
called for the first time, it fills the collection and return. For the further
requests, it will just return the collection which is already filled.
Values kept in static variables are accessible to all visitors in the
website. So you should take extra care when writing methods like the above. You
need locking because multiple visitors may call the GetAllProducts
method at the same time.
The above given example is an implementation of the " Singleton pattern [^] ".
Profiles
Session data is lost when the visitor leaves the webpage. What if you need
to persist all the user information for a long time? ASP.NET Profile is the answer. It provides a neat
way to persist information for a long time. Creating a profile is trivial. You
only need a few entries in the web.config file as seen below
<profile>
<properties>
<add name="Id" type="Int32"/>
<add name="Name"/>
<add name="Age" type="Int32"/>
</properties>
</profile>
ASP.NET generates a strongly typed class
for accessing profile data. Data type for the properties are chosen depending
upon the type
value. Default
type is string if no type is specified. Following code
shows setting values and reading back from profile.
Profile.Name = txtName.Text;
Profile.Id = int.Parse(txtPersonId.Text);
Profile.Age = int.Parse(txtAge.Text);
int age = Profile.Age;
string name = Profile.Name;
int id = Profile.Id;
ASP.NET keeps the profile data in
SQLServer database. If no databases are available in the project, it creates a
database file in the app_data
directory when it is used for the first time. Profiles are implemented using
the provider pattern. SQLProfileProvider
is the default profile provider. Profiles use windows authentication by
default. Profile object can be used with any authentication modes supported by ASP.NET.
Profile is very handy in many situations. However, it has the following
drawbacks
- It allows
to keep only serializable types
- Reading
data from profile requires database access which can potentially make your
application less performant. If your
website uses profiles heavily, you have to cache the results to avoid
unncessary database calls.
This is a
high level overview of profile. There are many other features profile offers
such as groups, anonymous access etc. Explaining whole profile detail is beyond
the scope of this article. Check
this [
^] MSDN article for more details.
Hacking ViewState
ViewState is already explained in the
previous section
[^] . Articles that talk about viewstate always say, it is less secure and not good
for keeping secure information. Let us see how a viewstate value can be hacked.
Data kept in Viewstate is serialized
using LosFormater
, a less
known class used for serialization. LosFormatter
is helpful to serialize simple types and it produces ASCII string
representation of the object graph. The following code shows using LosFormatter
.
[Serializable]
class Customer
{
public Customer(int age,string name) {
this.Age = age;
this.Name = name;
}
public int Age { get; set; }
public string Name { get; set; }
}
string Serialize() {
Customer customer = new Customer(25,"Navaneeth");
LosFormatter formatter = new LosFormatter();
using (StringWriter output = new StringWriter()) {
formatter.Serialize(output, customer);
return output.ToString();
}
}
The above code serializes the object graph and produces an ASCII string
which can be transmitted over HTTP.
The following code shows decrypting viewstate
values.
object HackViewstate(string viewStateValue) {
LosFormatter formatter = new LosFormatter();
return formatter.Deserialize(viewStateValue);
}
The following figure shows the contents of the object which is deserialized
This gives you a clear explanation of why secured data should not be kept on
viewstate.
Conclusion
This article tackled the state management techniques used in ASP.NET. You have learned what is HTTP protocol
and the need for state management. We discussed the stateless architecture of HTTP protocol and how a
website works.
In the second section, we discussed QueryString and how it helps to maintain
information across different pages. We also discussed about hackable URLs and
some best practices for using it.
The third section discussed the usage of cookies. We have seen the pros and
cons of cookies. We also discussed multi-valued cookies which helps to overcome
the number of cookies a website can set. Security constraints and a practical
example have also been discussed.
The next section discussed "Session
state" which provides more
sophisticated storage. We have seen how session works, session modes and best
practices for using it. We have also discussed about session timeout and
cookie-less sessions.
"Application state" is discussed in the next section.
Discussed about the events which are associated with session state and application
state. We have seen a practical example
where application state is very handy. Then we discussed about
storing the state in static(shared in VB) variables. We have seen the
lifetime of a static variables and how locking is used to synchronize access
between multiple threads. Profiles are very handy when you need to persist
information for long periods of time. We have discussed profiles in the next
section and seen simple usage of profiles.
Finally, we discussed viewstate hacking
techniques and proved secured information should not be kept on viewstate. We discussed about the serialization class
LosFormatter
and how it
works.
That's all about this article. I hope you will find it helpful. I'd
appreciate if you rate this article and leave your feedback below.
Thank you for reading, happy coding!