Académique Documents
Professionnel Documents
Culture Documents
10. SaveViewState: Saves the current data state of the control to ViewState.
After this stage any changes to the control data are lost.
11. Render: Generates the client-side HTML Dynamic Hypertext Markup Language
(DHTML) and script that are necessary to properly display this control at the
browser. In this stage any changes to the control are not persisted into
ViewState.
12. Dispose: Accepts cleanup code. Releases any unman-aged resources in this
stage. Unmanaged resources are resources that are not handled by the .NET common
language runtime such as file handles and database connections.
13. UnLoad
Authentication Levels
Forms authentication enables you to identify users with a custom database such
as an ASP.NET membership database. Alternatively you can implement your own
custom database. Once authenticated you can reference the roles the user is in to
restrict access to portions of your Web site.
Virtual functions implement the concept of polymorphism are the same as in C#, except that
you use the override keyword with the virtual function implementaion in the child class. The
parent class uses the same virtual keyword. Every class that overrides the virtual method will
use the override keyword.
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Shape.Draw") ;
}
}
ASP.NET provides the following ways for you to build redirection into your Web pages:
• Using hyperlinks on pages.
• Configuring cross-page posting, which enables you to specify an alternate target page
when the current page is submitted.
• Redirecting programmatically by forcing the browser to request a different page.
• Redirecting programmatically by transferring control to a different page in the same Web
application.
we know Http is an state-less protocol which is required for interaction between
clinet and server .
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.
Cons:
1)Cookie should contain non sensitive data as one can easily read cookies and they
result of which your security may be tampered .
2) Cookie should not contain large amount of information as they are sent back and
forth with request and response in between client and server which may cause your
Performance degradation
A cookie is stored on the client's machine by their web browser software. There are good levels
of compatibility in browser implementations so using them is generally hassle-free. When a web
server receives an HTTP request it responds with an HTTP response. To set a cookie we include
information in an HttpResponse that instructs the browser to save a cookie on the client's system.
Future HttpRequests will then include details of this and other cookies.
Be very clear about cookies; when you call HttpCookie.Add the cookie is not added to anything
except a collection in the HttpResponse that will be sent back to the web browser. The cookie is
only stored on the client's machine when the browser has successfully processed the instruction
to save the cookie that it received in an HttpResponse. We at the server can only check that
cookie has been saved when we receive another HttpRequest as we can then see whether the
request includes our cookie.
Note as well that cookies are strings and are invariably quite short (you cannot save objects in
cookies).
Attempt Free Asp.Net Interview Question Answer Online Test and check your
performance
What is the use of indexes and what are the types of indexes available in SQL
Server?
Indexes are used to find data quickly when a query is processed in any relational database.
Indexes improve performance by 10 to 500 times.
Index can improve the performance in following operations:
• Find the records matching with WHERE clause
C# provides two types—class and struct, class is a reference type while the other is a value type.
Here is difference between Value types and Reference types.
Value types directly contain their data which are either allocated on the stack or allocated in-line
in a structure. Reference types store a reference to the value's memory address, and are allocated
on the heap. With reference types, an object is created in memory, and then handled through a
separate reference—rather like a pointer.
Reference types can be self-describing types, pointer types, or interface types. Primitive types
such as int, float, bool and char are value types.
Variables that are value types each have their own copy of the data, and therefore operations on
one variable do not affect other variables. Variables that are reference types can refer to the same
object; therefore, operations on one variable can affect the same object referred to by another
variable.
Value types have a default implied constructor that initializes the default value. Reference types
default to a null reference in memory.
Value types derive from System.ValueType. Reference types derive from System.Object.
Value types cannot derive a new type from an existing value type, except for structs. Reference
types can derive a new type from an existing reference type as well as being able to implement
interfaces.
1 comments
Tags: C#, Microsoft .NET Framework
Explain the delegates in C#.
Delegates in C# are objects which points towards a function which matches its signature.
Delegates are reference type used to encapsulate a method with a specific signature. Delegates
are similar to function pointers in C++; however, delegates are type-safe and secure.
Here are some features of delegates:
• A delegate represents a class.
• A delegate is type-safe.
• We can use delegates both for static and instance methods
• We can combine multiple delegates into a single delegate.
• Delegates are often used in event-based programming, such as publish/subscribe.
• We can use delegates in asynchronous-style programming.
• We can define delegates inside or outside of classes.
Syntax of using delegates
//Declaring delegate
delegate void SampleDelegate(string message);
• A class can implement several interfaces but can inherit only one abstract
class. Means multiple inheritance is possible in .Net through Interfaces.
1 comments
Tags: Interview Question Answer, Object Oriented Programming
What is the use of Master Pages in Asp.Net?
A master page in ASP.Net provides shared HTML, controls, and code that can be used as a
template for all of the pages of a website.
Every master page has asp:contentplaceholder control that will be filled by the content of the
pages that use this master page.
You can create a master page that has header and footer i.e. a logo, an image, left navigation bar
etc and share this content on multiple pages. You need not to put these things on every aspx
page.
0 comments
Tags: ASP.NET 2.0, Interview Question Answer
What is the difference between .Net Remoting and Asp.Net Web Services?
• ASP.NET Web Services Can be accessed only over HTTP but .Net Remoting
Can be accessed over various protocols like TCP, HTTP, SMTP etc.
• Web Services are based on stateless service architecture but .Net Remoting
support for both stateful and stateless environment.
• .NET Remoting provides the fast communication than Web Services when
we use the TCP channel and the binary formatter.
• Web services support only the objects that can be serialized but .NET
Remoting can provide support to all objects that inherit MarshalByRefObject.
• Web Services are reliable than .Net remoting because Web services are
always hosted in IIS.
• Web Services are ease to create and deploy but .Net remoting is bit
complex to program.
0 comments
Tags: .Net Remoting, Interview Question Answer, Web Services
Newer Posts Older Posts Home
Twitter Updates
Followers
Subscribe To
Posts
Atom
Posts
All Comments
Atom
All Comments
My Blogs
• Project Management Tips
Popular Tags
• Interview Question Answer (8)
• Object Oriented Programming (5)
• Microsoft .NET Framework (4)
• ASP.NET Architecture (3)
• Database (3)
• C# (2)
• Microsoft SQL Server 2008 (2)
• sql query (2)
• .Net Remoting (1)
• ADO.NET (1)
• ASP.NET 2.0 (1)
• ASP.NET 3.5 (1)
• ASP.NET Controls (1)
• Asp.Net Performance Tips (1)
• Asp.Net Programming (1)
• Microsoft SQL Server (1)
• SQL Server (1)
• Web Services (1)
• XML (1)
• state management (1)
By default, the connection pool is created when the first connection with a unique connection
string connects to the database. The pool is populated with connections up to the minimum pool
size. Additional connections can be added until the pool reaches the maximum pool size.
When a user request a connection, it is returned from the pool rather than establishing new
connection and, when a user releases a connection, it is returned to the pool rather than being
released. But be sure than your connections use the same connection string each time. Here is
the Syntax
XSLT is based on template rules which specify how XML documents should be processed. An
XSLT processor reads both an XML document and an XSLT style sheet. Based on the
instructions the processor finds in the XSLT style sheet, it produce a new XML document. With
XSLT we can also produce HTML or XHTML from XML document. With XSLT we can
add/remove elements and attributes, rearrange and sort elements, hide and display elements from
the output file. Converting XML to HTML for display is probably the most common application
of XSLT today.
Introduction
In this article, we will take a closer look at how ASP.NET pages post back to themselves, and
how to customize this feature in our web applications.
This article discusses various options for state management for web applications developed
using ASP.NET. Generally, 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.
ASP.NET provides various client side state management options like Cookies, QueryStrings
(URL), Hidden fields, View State and Control state (ASP.NET 2.0). Let's discuss each of
client side state management options.
Bandwidth should be considered while implementing client side state management options
because they involve in each roundtrip to server. Example: Cookies are exchanged between
client and server for each page request.
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.
Let's see an example which makes use of cookies to customize web page.
if (Request.Cookies["UserId"] != null)
lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our
website!";
else
lbMessage.text = "Guest,welcome to our website!";
If you want to store client's information use the below code
Response.Cookies["UserId"].Value=username;
Advantages:
• Simplicity
Disadvantages:
• 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 used to store data at the page level. As its name says, these fields are not
rendered by the browser. It's just like a standard control for which you can set its
properties. Whenever a page is submitted to server, hidden fields values are also posted to
server along with other controls on the page. Now that all the asp.net web controls have
built in state management in the form of view state and new feature in asp.net 2.0 control
state, hidden fields functionality seems to be redundant. We can still use it to store
insignificant data. We can use hidden fields in ASP.NET pages using following syntax
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
View State can be used to store state information for a single user. View State is a built in
feature in web controls to persist data between page post backs. 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. To
reduce performance penalty, disable View State for all the controls for which you don't need
state. (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["myviewstate"] = myValue;
Advantages:
• Simple for page level data
• Encrypted
• Can be set at the control level
Disadvantages:
• 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. They are
passed along with URL in clear text. Now that cross page posting feature is back in asp.net
2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on
URL length. We can only pass smaller amounts of data using query strings. 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.
Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid
that goes to a product detail page, it would be an ideal use of the Query String to include
the product ID in the Query String of the link to the product details page (for example,
productdetails.aspx?productid=4).
When product details page is being requested, the product information can be obtained by
using the following codes:
string productid;
productid=Request.Params["productid"];
Advantages:
• Simple to Implement
Disadvantages:
• Human Readable
• Client browser limit on URL length
• Cross paging functionality makes it redundant
• Easily modified by end user
Control State:
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 behavior across post backs. Grid View is in no way
affected when we disable View State for the Grid View or entire page
Server Side State management:
As name implies, state information will be maintained on the server. Application, Session,
Cache and Database are different mechanisms for storing state on the server.
Care must be taken to conserve server resources. For a high traffic web site with large
number of concurrent users, usage
of sessions object for state management can create load on server causing performance
degradation
Application object:
Application object 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 changes infrequently. 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["mydata"]="mydata";
Application.UnLock();
Session object:
Session object is used to store state specific information per client basis. It is specific to
particular user. Session data persists for the duration of user session you can store session's
data on web server in different ways. Session state can be configured using the <session
State> section in the application's web.config file.
Configuration information:
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 vale 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.
In process mode:
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
Disadvantages:
• Session data will be lost if the worker process or application domain recycles
• Not ideal for web gardens and web farms
Out-of-process Session mode (state server mode):
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. You 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
Disadvantages:
• Out-of-process mode provides slower access compared to In process
• Requires serializing data
SQL-Backed Session state:
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.
Disadvantages:
• Requires serialization of objects
Choosing between client side and Server side management techniques is driven by various
factors including available server resources, scalability and performance. We have to
leverage both client side and server side state management options to build scalable
applications.
When leveraging client side state options, ensure that little amount of insignificant
information is exchanged between page requests.
Various parameters should be evaluated when leveraging server side state options including
size of application, reliability and robustness. Smaller the application, In process is the
better choice. We should account in the overheads involved in serializing and deserializing
objects when using State Server and Database based session state. Application state should
be used religiously.
Is your email address OK? You are signed up for our newsletters but your
email address has not been reconfirmed in a long time. To make this warning go
away please click here to have a confirmation email sent so we can confirm your
email address and continue sending you your newsletters. Alternatively, you can
update your subscriptions.
Top of Form
/w EPDw UKMTAy
/w EWCALn17PqD
Table of Contents
• Introduction
• HTTP protocol and the Need for State Management Techniques
• QueryString
○ QueryString Encoding
○ Reading QueryString Safely
○ Pros and Cons
○ Producing Hackable URLs
○ Securing QueryString
• Cookies
○ Some Useful Properties you Must Know Before Using Cookies
○ Multi-Valued Cookies
○ A Practical Example
○ Security Constraints
○ Pros and Cons
• Session State
○ How Session Works?
○ Session Timeout
Session Timing out Frequently
○ Where Session is Stored?
○ Usage and Best Practices
Wrapping Session in a Strongly Typed Class
Base Page Class Approach
• Application State
○ Understanding Session and Application Events
○ A Practical Example
• Keeping State in Static (shared in VB) Variables
• Profiles
• Hacking viewstate
• Conclusion
• History
Introduction
Recently Code Project started a beginners walkthrough for web development, an initiative for
organizing all the information required for web development under one article. I think it will be
helpful for beginners to get guidelines for web development. This article is my contribution to
the ASP.NET section where I describe the state management techniques and best practices
used when developing with ASP.NET.
Collapse
www.somewebsite.com/search.aspx?query=foo
The URL part which comes after the ? symbol is called a QueryString. QueryString has two
parts, a key and a value. In the above example, query is the key and foo is its value. You can
send multiple values through querystring, separated by the & symbol. The following code shows
sending multiple values to the foo.aspx page.
Collapse
Response.Redirect("foo.aspx?id=1&name=foo");
The foo.aspx page will get the values like in the following table.
Valu
Key
e
id 1
nam
foo
e
Collapse
string id = Request.QueryString["id"];
string name = Request.QueryString["name"];
Request.QueryString has two overloaded indexers. One accepts the key name and another a
zero-based index. The latter is useful when you don't know the query string names. If you try to
get a value which is not in the QueryString collection, you will get a NULL reference.
QueryString Encoding
The URL RFC [^] states that, a URL can have only ASCII characters. So all the other characters
should be encoded when you pass through the URL. The .NET Framework provides the
HttpServerUtility.UrlEncode class to encode the URL.
The following code shows how name and id is passed to foo.aspx page as encoded.
Collapse
string id = "1";
string name = "foo#";
string url = string.Format("foo.aspx?{0}&{1}", Server.UrlEncode(id),
Server.UrlEncode(name));
Response.Redirect(url);
// decoding can be done using it's counter part
HttpServerUtility.UrlDecode()
string id = Server.UrlDecode(Request.QueryString["id"]);
string name = Server.UrlDecode(Request.QueryString["name"]);
Note: HttpServerUtility is available to your code in all webforms through the Page.Server
property. Also you only need to encode those values which have non-ASCII characters, not all
the values.
Reading QueryString Safely
I have seen many people use code as shown below to read values from a QueryString collection
Collapse
Collapse
Collapse
// System.Object classes documentation for .NET 1.1
http://msdn.microsoft.com/en-us/library/system.object(VS.71).aspx
Collapse
Collapse
int personId;
if (int.TryParse(queryStringValue, out personId)) {
// check the edit permissions here
}
System.Security.Cryptography namespace has classes which help to encrypt strings. You can
pass the encrypted string through the URL, so that it is tamperproof and secure up to a certain
extent.
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
Collapse
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
Collapse
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.
Collapse
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.
Collapse
// this cookie expires after one day from the date it is set
// browser will take care about removing the cookies after the expiry time
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
Collapse
// for safety, always check for NULL as cookie may not exist
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
Collapse
Response.Cookies["id"].Expires = DateTime.Now.AddDays(-1);
Cookies can be accessed using java script. Setting this property prevents
HttpOnly
cookies being accessed from java script
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
Collapse
Collapse
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.
Collapse
Session["name"] = "Navaneeth";
Session accepts a System.Object type. So you need a type cast when reading. Reading values
from session is like
Collapse
Session.Clear() / Clears all contents of the session. This will not end the
Session.RemoveAll() session
Collapse
Collapse
<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.
Collapse
<sessionState
timeout="60" />
or
Session.Timeout = 60;
performant as it
reads from the
same processes
memory and it
allows you to
keep all .NET process will
types. If session affect the
mode is not session data.
specified,
ASP.NET will
use InProc as
the default
mode.
StateServer
mode provides
a basic level of
isolation for the
data storage. It
runs as a
It is less
separate
performant
windows service
compared to
<sessionState Server and keeps the
InProc mode. But
mode="StateServer" memory session data out
StateSer this helps you to
stateConnectionString= as a of ASP.NET
ver "tcpip=Yourservername:42424" seprate process avoid loosing
/> session data
process memory area.
when ASP.NET
To access
worker process
session,
restarts.
ASP.NET
process has to
communicate
with this
external
process.
to keep session
data in
SQLServer. This
is helpful when
your web e types
application is
hosted in a
webfarm.
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
Collapse
Collapse
Collapse
Collapse
Collapse
Collapse
Collapse
Collapse
}
}
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.HttpApplicationState 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.
Collapse
Application_St This event executes when application initializes. This will execute
art when ASP.NET worker process recycles and starts again.
Application_E
Executes when the application ends.
nd
Executes when session ends. Note : this event will be fired only if you
Session_End
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.
Collapse
Collapse
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 product is NULL, loading all products and returning
if (products != null) {
lock (locker) {
if (products != null) {
// fill the products here
}
}
}
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
Collapse
<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.
Collapse
Profile.Name = txtName.Text;
Profile.Id = int.Parse(txtPersonId.Text);
Profile.Age = int.Parse(txtAge.Text);
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.
Collapse
[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() {
// formatting
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.
Collapse
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!
Bottom of Form