Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Monday, February 1, 2010 1:30 AM
I had one question which frequently asked in the interview.<o:p></o:p>
When you will prefer session, caching, view state, Query String? What is the difference in there data storing methods. What are the advantages and disadvantages?<o:p></o:p>
All replies (7)
Monday, February 1, 2010 3:51 AM ✅Answered
View state refers to the page-level state management mechanism, which is utilized by the HTML pages emitted by ASP.NET applications to maintain the state of the web form controls and widgets. The state of the controls is encoded and sent to the server at every form submission in a hidden field known as __VIEWSTATE. The server sends back the variable so that when the page is re-rendered, the controls render at their last state. At the server side, the application might change the viewstate, if the processing results in updating the state of any control. The states of individual controls are decoded at the server, and are available for use in ASP.NET pages using the ViewState collection.
The main use for this is to preserve form information across postbacks.
In World Wide Web, a query string is the part of a Uniform Resource Locator (URL) that contains data to be passed to web applications such as CGI programs
When a web page is requested via the Hypertext Transfer Protocol, the server locates a file in its file system based on the requested URL. This file may be a regular file or a program. In the second case, the server may (depending on its configuration) run the program, sending its output as the required page. The query string is a part of the URL which is passed to the program. Its use permits data to be passed from the HTTP client (often a web browser) to the program which generates the web page.
Session state is a collection of user-defined session variables, which are persisted during a user session. These variables are unique to different instances of a user session, and are accessed using the Session collection. Session variables can be set to be automatically destroyed after a defined time of inactivity, even if the session does not end. At the client end, a user session is identified either by a cookie or by encoding the session ID in the URL itself.
ASP.NET supports three modes of persistence for session variables:
In Process Mode
The session variables are maintained within the ASP.NET process. This is the fastest way; however, in this mode the variables are destroyed when the ASP.NET process is recycled or shut down. Since the application is recycled from time to time this mode is not recommended for critical applications, rather in practice this mode is not recommended for any applications.
ASPState Mode
In this mode, ASP.NET runs a separate Windows service that maintains the state variables. Because the state management happens outside the ASP.NET process and .NET Remoting must be utilized by the ASP.NET engine to access the data, this mode has a negative impact on performance in comparison to the In Process mode, although this mode allows an ASP.NET application to be load-balanced and scaled across multiple servers. However, since the state management service runs independent of ASP.NET, the session variables can persist across ASP.NET process shutdowns.
The same problem arises though - since session state server runs as a single instance it is a single point of failure as far as session state is concerned. This service can not be load balanced and also imposes restrictions on types that can be stored in a session variable.
SqlServer Mode
In this mode, the state variables are stored in a database server, accessible using SQL. Session variables can be persisted across ASP.NET process shutdowns in this mode as well. The main advantage of this mode is it would allow the application to balance load on a server cluster while sharing sessions between servers. This is the slowest method of session state management in ASP.NET.
In computer science, a cache is a collection of data duplicating original values stored elsewhere or computed earlier, where the original data is expensive to fetch (owing to longer access time) or to compute, compared to the cost of reading the cache. In other words, a cache operates as a temporary storage area where frequently accessed data can be stored for rapid access. Once the data is stored in the cache, it can be used in the future by accessing the cached copy rather than re-fetching or recomputing the original data.
Often an application can increase performance by storing in memory data that is accessed frequently and that requires significant processing time to create. For example, if your application processes large amounts of data using complex logic and then returns the data as a report accessed frequently by users, it is efficient to avoid recreating the report every time a user requests it. Similarly, if your application includes a page that processes complex data but that is updated only infrequently, it is inefficient for the server to recreate that page on every request.
To help you increase application performance in these situations, ASP.NET provides caching using two basic caching mechanisms. The first is application caching, which allows you to cache data you generate, such as a DataSet or a custom report business object. The second is page output caching, which saves the output of page processing and reuses the output instead of re-processing the page when a user requests the page again.
Monday, February 1, 2010 3:56 AM ✅Answered
check below link
| state Management |
| http://dotnetslackers.com/Community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspx |
| Nine Options for Managing Persistent User State in Your ASP.NET Application |
| http://msdn.microsoft.com/en-us/magazine/cc300437.aspx |
Monday, February 1, 2010 4:17 AM ✅Answered
Well you need to go through some good article on state maintenance for sure. but i can for sure provide you with a starter.
Session is a server side state maintenance technique. that means it is stored on the server so the two obvious advantages are that it does not eat up much of your bandwidth and it is much secure again because it is on the server and sent through the unsecure and venurable network. ya the other side, it has a disadvantage as it accumulates on the server so might just get heavy.
View state is a client side state maintenance technique so heres a disadvantage that it eats up your bandwidth as it comes and goes with every request response cycle. but unlike other client side techniques, it is secure as it is encrypted before beign sent by asp.net server only so its not human readable. the basic difference between viewstate and session is that a viewstate created on a webpage cannot be accessed anywhere else but a session once created can be accessed anywhere unless it has not been cleared or expired.
Query String, another client side technique. you must have seen it in the address bar of your browser. anything that follows '?' in the address is the query string. like 'http://mydomain/default.aspx?id=123' here 123 is the value of the query string variable 'id'. so its human readable and editable and thus not secure ya but obviously light. and moreover it is just to pass values from one page to another.
You should preffer query string when data is not that confidential or if it is, must be encrypted and the values are just to be passed from one page to another. Use viewstate for senstive data to be used on just a single page. use session for senstive data to be shared on any page of the website.
As for caching, it is used to make the website fast. basically, we keep the output of a web page or a control on the server and when it is requested, rather than regenerating it, the stored output is displayed. you can configure it to depend upon several parameters and thus would regenrate itself if any of the parameter expires.
hope this helps but do read a good article on state maintenance to get a better idea of all this
Monday, February 1, 2010 4:41 AM ✅Answered
Session is for saving data specific to the user.
Cache is for caching data that is not user specific but app wide.
View state is for saving state on a page between post backs (avoid it if you can)
Query strings are used to pass data between pages.
Monday, February 1, 2010 6:06 AM ✅Answered
Hi Ambujnema,
You are correct, this is one of the question which is frequently asked in the interview because when you are dealing with a web application, performance always matters. Here is the advantages and disadvantages you can point out:
[But I believe that what you call a disadvantage can might be a advantage from other prespective, so it's all depends upon the requirement]
** View State:** It stores in a hidden field in the web form. Insecure. Scope is upto the postback for a single page. If you store large amount of data, performace will be slow down.
Query String: Carry string data[limited amount], scope it's upto the target page, it's temporary storage because when user close the browser or paste another URL data will be lost.
Caching: It stores allmost all data types, stores in server memory, it's very secure, useful for storing very large amount of data,can be global to all user & all pages.
Session: It is very secure because data never transmitted to client, stores at server side, storing large amount of data may slow down the performance, lifetime is default 20 min but can be altered.
So, as mentioned by you these are the storage medium in asp.net and I do not want to critisize anyone of them because they have there own imporatnce in asp.net. although we have other methods also to store info, like cookies, profiles, application state etc. but they require almost dozens of page to explain.
I think I am able to provide you the sumarize theory of storing medium. If you have any doubt or question related to this, please continue the thread.
Thanks
Tuesday, February 2, 2010 3:23 AM ✅Answered
Hi,
Application - Stored on the server and shared for all users. Does not expire. Deprecated by Cache (below).
Cache - Stored on the server and shared for all users. Can expire.
Session - Stored on the server. Unique for each user. Can expire.
ViewState - Stored in a hidden page input (by default). Does not expire.
Cookies - Stored at the client. Can expire.
QueryString - Passed in the URL. Must be maintained with each request.
in Detail,
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
**View State:
**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;
//Reading items from ViewState
Response.Write(ViewState["myviewstate"]);
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:
**<sessionState mode = <"inproc" | "sqlserver" | "stateserver">
cookieless = <"true" | "false">
timeout = <positive integer indicating the session timeout in minutes>
sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
server = <The server name that is only required when the mode is State Server>
port = <The port number that is only required when the mode is State Server>
**Mode:
**This setting supports three options. They are InProc, SQLServer, and State Server
Cookie less:
This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.
Timeout:
This indicates the Session timeout 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; 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
Wednesday, February 17, 2010 3:50 AM
it purely depends on the senario
suppose u want to keep important data throughout site then session is preferable
if for same page viewstate is ok
querystring for passing values that are not dangerous if user knows it too.
caching is temporary data which may be cleared by user so be careful to use.
Partial caching can be done.