/* ------------------------ My Meta Content Here SEO ------------------------ */

Pages

Main Menu

Monday, October 28, 2019

ASP.NET Session Management Techniques State Management in ASP.NET

What are the different Session state management options available in ASP.NET?


State Management in ASP.NET
  • A new instance of the Web page class is created each time the page is posted to the server.
  • In traditional Web programming, all information that is associated with the page, along with the controls on the page, would be lost with each roundtrip.
  • The Microsoft ASP.NET framework includes several options to help you preserve data on both a per-page basis and an application-wide basis.
    These options can be broadly divided into the following two categories:

    • Client-Side State Management Options
    • Server-Side State Management Options
Client-Side State Management
  • Client-based options involve storing information either in the page or on the client computer.
  • Some client-based state management options are:

    • Hidden fields
    • View state
    • Cookies
    • Query strings
Server-Side State Management
  • There are situations where you need to store the state information on the server side.
  • Server-side state management enables you to manage application-related and session-related information on the server.
  • ASP.NET provides the following options to manage state at the server side:

    • Application state
    • Session state
State Management

What is Query String in ASP?


Answer: A QueryString is a collection of characters input to a computer or web browser. A Query String is helpful when we want to transfer a value from one page to another. When we need to pass content between the HTML pages or aspx Web Forms in the context of ASP.NET, a Query String is Easy to use and the Query String follows a separating character, usually a Question Mark (?). It is basically used for identifying data appearing after this separating symbol. A Query String Collection is used to retrieve the variable values in the HTTP query string. If we want to transfer a large amount of data then we can't use the Request.QueryString. Query Strings are also generated by form submission or can be used by a user typing a query into the address bar of the browsers.

Syntax of Query String
Request.QueryString(variable)[(index).count]

Query String

Advantages:
  • Simple to Implement
  • Easy to get information from Query string.
  • Used to send or read cross domain (from different domain).
Disadvantages:
  • Human Readable
  • Client browser limit on URL length
  • Cross paging functionality makes it redundant
  • Easily modified by end user

Different methods of session maintenance in ASP.NET?


Session is a State Management Technique. A Session can store the value on the Server. It can support any type of object to be stored along with our own custom objects. A session is one of the best techniques for State Management because it stores the data as client-based, in other words the data is stored for every user separately and the data is secured also because it is on the server.

We can set the session on one of the following 2 types of configuration files:
  1. Machine Configuration file: Machine Configuration is applied for all application.
  2. Application Configuration file: It's applied for only application by application basis.

    Application Configuration file
Session Mode
In ASP.NET there are 4 types of Session Mode.

Off: We can disable the session mode for the entire application using the off mode.

ASP.NET page

According to performance and durability the difference between InProc,State Server and SQL Server is:
Session modePerformance Durability
InProcMore(1 processor and 1 server) less.
State ServerMedium(n processor and 1 server) Medium
SQL ServerLess More

1. InProc
The InProc Session mode is the default Session Mode. Using this Session Mode the Session Mode is stored in the application worker process (aspnet_wp.exe) in the application domain. The Worker Process is dependent on the IIS server version. The memory location was handled by the ASP.NET worker thread. It only involves a considerable overhead for the worker thread to manage these. Also, since this is in the memory of server, chances are that large session information would lead to more memory usage and thus lowering the performance.
I had explained by an example the use inproc session mode.

In Inproc Session mode the important point is:

1. When we get the WebForm2 then if we end the task of aspnet_wp.exe from the Task Manager and then again reload the WebForm2 then you will get no output, that means that all the sessions are stored in a worker process and after closing the task the session will be lost.

The following are the advantages of the InProc mode:
  1. Inproc session mode is very easy to implement, the only thing that is required is sessionState mode="InProc".
  2. It will perform fast because the session is kept on the web server within the ASP.NET Worker Process.
  3. Data is stored separately and the data is secure so it is suitable for web applications.
  4. In this mode there is no need to serialize and deserialize the object for storage and retrieval of the data.
The following are the disadvantages of InProc mode:
  1. Session data is lost when the worker process or application process is recycled.
  2. Not Suitable for WebFarms and WebGardens: In a webFarm that the web application is deployed on the various web servers.



    If the client sends the request and the request goes to the server load balancer and then it sees which Web Server is needed to be used, for example if the Web Server1 is needed to be used then the request goes to WebServer1 and the session variable is stored in Web Server1 and if we refresh web form2 and again make a request to Web Form2 then the server load balancer sends the request to web server2 and the session variable is not stored in Web Server2 so the session variable is lost. So the InProc mode is dependent on the Web Server.
  3. Increase the load of server
    In Session Mode the sessions are stored on the web server. If the number of sessions is increased then the load of the server is also increased and the scalability could be an issue.
2. StateServer
This is also the Out-Proc Session mode. StateServer uses a stand-alone Windows Service that is independent on IIS and can also be run on a separate server. This session state is totally managed by aspnet_state.exe. And the Session Variables are stored in an ASP.NET State service.

Now configure with the ASP.NET State Service.

Step 1: Go To Start and from there go to "Run" and type "services.msc" as in the following:



Step 2: Now open the Services Management Window and right-click on ASP.NET State Service and start the service; by default these services are stopped.



Step 3: For configuration with web.config write the code to web.config file.
  1. "StateServer" stateConnectionString="tcpip=localhost:42424">  
Generally the state services and web services are not in the same machine of a dedicated server so for the connection we need to write the stateConnectionString and here we need to provide the IP address or the name of the machine where the state service is running and here my services are run on localhost and 42424 is the port number.

The ASP.NET State Services can be present on a Web Server or a dedicated machine. So if we closed the worker Process (aspnet_wp.exe) then it is also not affected.



When the client sends a request to the web server, the web server stores the session data on the state server. The StateServer may be the current system or a different system. But it will be totally independent of IIS. The destination of the StateServer will depend on the web.config stateConnectionString setting. If we set it to localhost:42424 then it will store data in the local system itself. For changing the StateServer destination, we need to change the IP and ensure aspnet_state.exe is up and running on that system. Otherwise you will get the following exception while trying to store data on the session.

Advantage of State Service
  1. No issue about Worker Process because it's not dependent on Worker Process.
  2. Can be used with Web Farm and Web Garden: It supports a Web Farm and Web Garden both



    When a client sends a request of WebForm1.aspx then the server load balancer checks which server needs to the used and if the request goes to web server1 then web server sees the request store the session on the state server and again provides the response of WebForm2.aspx and now if the client again sends a request of webform2 and the load balancer provides the request to web server2 and then web server2 has the web.config file and it sends a request to the state server and the state server already has a session so it provides the response.
  3. Scalability is also increased because it keeps data separate from IIS.
Disadvantage of State Service
  1. Performance Decrease
    When the request goes to the server the object is serialized and deserialized so for that the performance is decreased so it is slower than the OnProc State Mode.
  2. If the request goes to the server and for some reason the ASP.NET State Service is restarted then all the sessions will be destroyed.

3. SQL Server

In this mode the session data is stored inside the SQL Server database so to store the session in the database we need to follow these steps.

Step 1: From the command prompt, go to your Framework version directory,  for example: c:\windows\microsoft.net\framework\. and search for the aspnet_regsql.exe that in which version these files are present and execute the file in the command prompt.



Parameter Description:
  1. ssadd: Add support for SQLServer mode session state.
  2. sstype p: P stands for Persisted. It persists the session data on the server.
  3. S : Server name.
  4. U : User name.
  5. P : Password.
  6. E : Authentication using the windows credential of the currently logged on users.
Step 2: After executing the command, open the database:



Step 3: Now for configuration we need to write the connection string in the web.config file:



Step 4: And the webfrom1.aspx and webform2.aspx code are the same.

Step 5: Now after sending a request to the server open the database and here the session id is stored and by default its expiration time is 20 minutes.



The following are the advantages of SQLServer mode:
  1. SQL Server is a more reliable and secure option.
  2. It's not dependent on the Worker Process and ASP.NET State Service so if it restarts then it is also not affected by the session.
  3. It is useful for a Web Farm and Web Garden: it is the same as State Server mode. It works the same also, the only difference is that the session is stored on the SQL server Database.


  4. Scalability: The scalability is increased compared to InProc and State Server because the session is stored in the database, no matter how many requests on the web server.
The following are the disadvantages of SQLServer mode:
  1. It's slower than StateServer and InProc Session mode.
  2. It must be serialized and deserialized.
The following are the reasons to use the SQLServer Session mode:
  1. When we need a session with more security, in other words we need that the data of the session is more secure.
  2. If there happen to be frequent server restarts, this is an ideal choice.
  3. We can use SQLServer session mode when we need to share sessions between two different applications.
According to performance and durability the difference between InProc, State Server and SQL Server is:
Session modePerformanceDurability
InProcmore(1 processor and 1 server)less
State ServerMedium(n processor and 1 server)Medium
SQL ServerLessMore
4. Custom
Using this session mode we can control everything, like session id and all it means that you can create your own algorithm to create a session id. It uses less something compared to others. You can create your own session state provider for example: Oracle.

The method of the implement of the custom session mode is:



Step 1: The initialize method sets the custom provider and provides the connection with the provider.
Step 2: SetItemExpireCallback is used to set the expiration time.
Step 3: InitializeRequest is called on every request and CreateNewStoreData is used to create a new instance of SessionStateStoreData.

Now configure with the web.config file as in the following:
  1. "Custom" customProvider="demo">  
  2.     
  3.      "demo" type="CustomDataType" />  
  •  
  •   
  •  
    The following are the advantages of custom session mode:
    1. We can use an existing table for storing the session data
    2. It's not dependent on IIS.
    The following are the disadvantages of custom session mode:
    1. Processing of data is very slow
    The following is when should we use should use a custom control:
    1. When we want to create our own session id.
    2. Where we want to store session data in other location
    3. When we need to use an existing table to store session data.

    Cookieless session


    The session id is stored as a cookie on the client machine. The session id is then used by the web server to identify if the request is coming from the same user or a different user.

    Now by taking a previous example if we give the request to the server of webForm1.aspx and store the cookies and give the response and here go to the browser and right-click on the browser and go to inspect element or press F12.



    Here this is the Session Id that was stored in the cookies, it will never change if we run webForm1 or WebForm2 because for a specific client or browser it is unique. But if by default cookies are disabled on the client machine then we need to configure it in the web.config file as in the following:
    1. "InProc" cookieless="true" 
    And if we run the webForm1 then we get the session id in the URL and it is sent back between the client and Web Server with every request and response.




    Both the session ids are the same and if we change the session id from the URL and refresh the page it goes to the server and the server thinks that the request comes from a different user so it never provides the required output.

    Remove Session
    Mostly we can remove session using one of the following 4 methods:
    1. Session.Remove(strSessionName):- Removes an item from the session state collection
    2. Session.RemoveAll():- Removes all items from the session collection.
    3. Session.Clear():- it is same as sesion.RemoveAll() method.
    4. Session.Abandon():-Cancels the current session.

    Enable and Disable Sessions


    We can enable and disable session state in one of two ways:
    1. Page Level: We have the attribute of page level that EnableSessionState
      1. <%@ Page Language="C#" EnableSessionState="False" 
      It disables the session state.

      We can make it read-only also. This will permit access to session data but will not allow writing data on the session.
      1. <%@ Page Language="C#" EnableSessionState="ReadOnly" 
    2. Application Level: Disables a Session for an entire web application; we need to use this at the application level. Set the property EnableSessionState in Web.Config.
      1. "false"> 
    The following are the advantages of session:
    1. It is easy to implement.
    2. Store data separately.
    3. Session is secure and transparent from the user.
    The following are the disadvantages of session:
    1. Performance decrease if we do not use InProc Session mode.
    2. Overhead involved in serializing and de-serializing session data.

    No comments:

    Post a Comment

    My Blog List

    • काश - काश मुझे भी पीने की आदत होती,मैं कब का मुर्दा हो गया होता। छुटकारा मिलता आज के आतंकवाद से, किसी संतान भूमि में सो गया होता। मेरा एतबार कौन करेगा, मैंने मुर...
      3 months ago
    • काश - काश मुझे भी पीने की आदत होती,मैं कब का मुर्दा हो गया होता। छुटकारा मिलता आज के आतंकवाद से, किसी शमशान भूमि में सो गया होता। मेरा एतबार कौन करेगा, मैंने मुर...
      3 months ago
    • Kumaon University Nainital B.Ed entrance exam test result 2012 - कुमाऊँ विश्वविधालय, नैनीताल (उत्तराखण्ड)
      10 years ago