• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Friday, July 28, 2017

ASP.NET State Management

 Abhishek Tomer     July 28, 2017     Asp.Net, Asp.Net MVC     4 comments   

State management is a technique or way to maintain / store the state of an Asp.Net controls, web page information, object/data, and user in the application. Because a web applications are stateless means on each page posted to the server, the state of controls is lost.

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
Server Side State management Techniques
  • Application State
  • Session State
ASP.NET State Management
Client Side Sate management: -
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 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
  1. Application State variables are stored on the web server.
  2. Application State variables are cleared, only when the process hosting the application is       restarted, that is when the application ends.
  3. Application State variables are not shared across a Web Farm or a Web Garden.
  4. 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();
    
  5. 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.
Application events in ASP.NET
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:-
  1. Find the total number of visitor globally.
  2. Handel the whole application exception globally.
Session Sate
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
  1. Session value is present until or unless server restart .
  2. We can be used with web farms and web gardens.
  3. State server provide more scalability than InProc.
Disadvantages
  1. StateServer is slower than InProc
  2. Complex objects, need to be serialized and deserialized
  3. If the StateServer, is on a dedicated machine, and if the server goes down all the sessions are lost.
In SQL Server mode: In this mode session values store in the SQL server process database. On each request and response.
  • Following step to configure asp.net web application to use SQLServer mode:
  1. 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
  2. Type - aspnet_regsql.exe -S SQLServerName -E -ssadd -sstype p
  3. Press Enter. At this point you should have ASPState Database added.
  4. 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 windows authentication

        
         For sql serevr authentication

         
Advantages
  1. SQL Server is the most reliable option because it is survives worker process recycling and SQL Server restarts.
  2. It can be used with web farms and web gardens.
  3. It is more scalable than State server and InProc session state modes.
Disadvantages
  1. Slower than StateServer and InProc session state modes
  2. Complex objects, need to be serialized and deserialized
Note:
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 ðŸ˜‰
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

4 comments:

  1. IT TutorialsMarch 30, 2018 at 7:06 PM

    Thanks for your informative article. understandable explanation about statemanagemnt concepts. Dot Net Training in Chennai

    ReplyDelete
    Replies
      Reply
  2. rmouniakOctober 10, 2018 at 9:49 AM

    I like your blog, I read this blog please update more content on hacking,
    Nice post,and good information Thanks for sharing
    further check it once at Dot NET Online Course Hyderabad

    ReplyDelete
    Replies
      Reply
  3. adityaOctober 18, 2021 at 10:51 AM


    Very 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

    ReplyDelete
    Replies
      Reply
  4. SooriyaJanuary 12, 2022 at 6:03 PM

    How to select niche for blogging?
    Blog 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!

    ReplyDelete
    Replies
      Reply
Add comment
Load more...

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • ASP.NET State Management
    State management is a technique or way to maintain / store the state of an Asp.Net controls, web page information, object/data, and user in ...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Static Files Middleware in ASP.NET Core
    In this article, I am going to discuss how to serve static files using Static Files Middleware in ASP.NET Core Application. Please read ou...
  • HTTP Client Message Handler in Web API
    In this article, I am going to discuss HTTP Client Message Handler in Web API with real-time examples. As we already discussed in HTTP Mes...
  • ASP.NET Web API Basic Authentication
    In this article, I am going to discuss how to implement the ASP.NET Web API Basic Authentication step by step with an example. Please read...
  • Kestrel Web Server in ASP.NET Core
    In this article, I am going to discuss the Kestrel Web Server in ASP.NET Core Application. Please read our previous article before proceed...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape