Why we need of ASP.NET State Management
As we know that A Web Applications work on HTTP protocol and a HTTP protocol is a stateless protocol, meaning it does not retain state between client server requests. That’s we need to prevent store the state of an Asp.Net controls, web page information, object/data, and user in the application on each request response.
Example: - When we fill a registration form as a customer on an E-commerce Side and submit the button then we can see that all the value of text box are blanked automatically because when a client (your browser) submit the form then it send the request to server and server send back the response to that client between this communication all information associated with the page and the controls on the page would be lost with each round trip. Suppose a user filed the form but some field of form is not filed and hit submit button then all information of all filed are lost and user need to filed all information again. To retain the page state Microsoft provide the different technique to maintain or store the state of the page or application until user session end.
ASP.NET provides us with 2 ways to manage the state of an application.
Client Side State management Techniques
- View State
- Hidden field
- Query Strings
- Cookies
- Application State
- Session State
Client Side State management Techniques: - This technique is used to maintain or store the information on client machine (Web Browser).
There are following technique to use for Client Side State management.
(1) ViewState: - ViewState can be used to maintain the State of page information at page level. The term "Page Level" means that the information is being stored for a specific page and until that specific page is active (i.e. the page which is being currently viewed by the user). Once the user is re-directed or goes to some other page, the information stored in the View State gets lost. By default each Asp.Net control have EnableViewState=True. But can also disable the EnableViewState property at server control, page and configuration file level by setting the EnableViewState=False property.
Note: When an Asp.net web page rendered on browser then View State value is stored in a hidden field as Hashed Format on the page.
To set A value in ViewState Variable
ViewState[“Key”]=”Your value”;To Get A value in ViewSate Variable
String Name= ViewState[“Key”].ToString();Use: - This is useful to retain the textbox value when post back event fired.or to retains a variable value in code behind because it is accessible on a single page.
(2) Hidden Filed: - Hidden Filed is same as view sate but it can be used in different style and hidden filed value is not visible to end user when page rendered.
int newVal = Convert.ToInt32(HiddenField1.Value) + 1;
HiddenField1.Value = newVal.ToString(); Label2.Text = HiddenField1.Value;Use: - If you want to store a user id in hidden filed when end user edit the from because we do not want to edit the user id by end user and during save the form we can get value from that hidden field. Hidden filed is not visible to end user.
Query String: - Query String can be used to send information from one page to other page from the URL.
Send UserID value by Query String from PageA To PageB
Response.Redirect(“/PageB?UserID=100);Receive UserID value by Query String from PageB URL
Var QueryStringvalue=Request.QueryString[“UserID”];Server Side Sate management: -
This technique is used to maintain or store the information on web server or SQL server database.
There are two type of technique use to maintain the session state
- Application State
- Session State
Application object is used to store the information globally across entire application and shared across multiple user sessions. Application State object are like multi-user global data.
Set value to Application Object
Application["GlobalVariable"] = 0;Get value from Application Object
Lable1.Text= Application["GlobalVariable"];Some Key Points
- Application State variables are stored on the web server.
- Application State variables are cleared, only when the process hosting the application is restarted, that is when the application ends.
- Application State variables are not shared across a Web Farm or a Web Garden.
- Application state variables are not thread safe. Lock and Unlock methods of the application class must be used to protect against race conditions, deadlocks, and access violations.
Application.Lock(); Application["GlobalVariable"] = (int)Application["GlobalVariable"] + 1; Application.UnLock();
- Use application state variables only, when the variables need to have global access and when you need them for entire time, during the life time of an application. Cache object, can be used, as an alternative, if you need to have global access for a certain duration.
Following event present in Global.asax.cs file.
Application_start: The Application_Start event is fired when a user hit application name on URL. Note this event is fired only first time for one user.
void Application_Start(object sender, EventArgs e) { Application["CountNumberOfVisitor"] = 0; }Application_Error: It is fired when an unhandled exception occurs in whole application, we can manage exception handling globally by this event.
Application_End: The Application_End event is raised just before an application domain ends because of any reason, it may IIS server restarting or making some changes in an application cycle or global configuration files.
Use:-
- Find the total number of visitor globally.
- Handel the whole application exception globally.
Application object is used to store the information across all pages, but only for a given single session. Session variables are like single-user global data.
Generally session is used to store user's information that is uniquely identify on browser. The server maintains the state of user information by using a session ID. When users send a request to server without a session ID then server creates a session ID for that request and sends back to client with every request and response to the same user.
So by this session ID a user can identify on the web application.
Set value to Session Object
Session ["GlobalVariable"] = 0;Get value from Session Object
Lable1.Text= Session["GlobalVariable"];Session Events in ASP.NET
Session_Start: The Session_start event is fired every time a new user makes a request without a session ID, i.e., new browser accesses the application, then a session_start event raised. Let's see the Global.asax file.
void Session_Start(object sender, EventArgs e) { Session["ShoppingCartCount"] = 0; // Code that runs when a new session is started }Session_End: The Session_End event is fired when session ends either because of a session time out expiry or explicitly by using Session.Abandon(). The Session_End event is fired only in the case of In proc mode not in the state server and SQL Server modes.
There are four session storage mechanisms provided by ASP.NET
In Proc mode:- In proc mode is the default mode and session values are stored in the web server's memory (in IIS). If there are more than one IIS servers then session values are stored in each server separately on which request has been made by client. Since the session values are stored in server, whenever server is restarted the session values will be lost. Default session time out is 20 min
In State Server mode:- In this mode session values store session in the web server process that is called as asp.net state service. This process is different from the asp.net worker process. The asp.net state service can be present on a web server or a dedicated machine before or after restart the web server.
Note: - To Start ASP.NET State Service we need to type services.msc in CMD windows and click OK. And right clicked on Start ASP.NET State Service and click start.Advantages
- Session value is present until or unless server restart .
- We can be used with web farms and web gardens.
- State server provide more scalability than InProc.
- StateServer is slower than InProc
- Complex objects, need to be serialized and deserialized
- If the StateServer, is on a dedicated machine, and if the server goes down all the sessions are lost.
- Following step to configure asp.net web application to use SQLServer mode:
- Create the ASPState database using aspnet_regsql.exe tool.
Type cd C:\Windows\Microsoft.NET\Framework64\v5.0.30319 in command prompt in my case I have use dot net framework v5 and press enter - Type - aspnet_regsql.exe -S SQLServerName -E -ssadd -sstype p
- Press Enter. At this point you should have ASPState Database added.
- For help running this tool
Visit at: http://msdn.microsoft.com/en-us/library/ms229862(v=vs.100).aspx
- Set the Session state mode=SQLServer and sqlConnectionString
For sql serevr authentication
Advantages
- SQL Server is the most reliable option because it is survives worker process recycling and SQL Server restarts.
- It can be used with web farms and web gardens.
- It is more scalable than State server and InProc session state modes.
- Slower than StateServer and InProc session state modes
- Complex objects, need to be serialized and deserialized
Web Garden - Web application deployed on a server with multiple processors
Web Farm - Web application deployed on multiple server
Cookie less sessions
As we know that By default sessions use cookies and session-id is stored as a cookie on the client computer which is provided by server when user send the request first time and session-id is used to identify if the request is coming from the same user or a different user.
Cookie less session mainly used if a user disabled the cookies from his or her browser and if we user the session variable to manage the user then sessions may not work as expected.
We can reduce this problem by setting cookieless="true" in web configuration file as:
For Set the cookieless session to true
After setting this we can see that session ID present of URL with question mark and used to each request and response.
Summary:
So, Guys this is all about State Management in Asp.Net.
I Hope in this post I have covered all the points about State Management which will be helpful to understand the concept of Maintaining state of your Application.
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Thanks for your informative article. understandable explanation about statemanagemnt concepts. Dot Net Training in Chennai
ReplyDeleteI like your blog, I read this blog please update more content on hacking,
ReplyDeleteNice post,and good information Thanks for sharing
further check it once at Dot NET Online Course Hyderabad
ReplyDeleteVery wonderful informative article. I appreciated looking at your article. Very wonderful reveal. I would like to twit this on my followers. Many thanks!
bulletintech
how tall is dababy
henry sedgwick v
justdubs
citra emulator apk
frank rocky fiegel
how to program rca universal remote
taylor olsen
natalie 90 day fiance
How to select niche for blogging?
ReplyDeleteBlog vs Vlog: Which is perfect for 2022?
10 amazing ways to earn with blogging
Top 8 websites for copyright free images
What is Personal blog Meaning? How to start & earn money through it?
The 7 Strategies About Content Writing Only A Handful Of People Execute (With a bonus hack)
Top 5 Mailchimp alternatives that will blow your mind!