Why State Management Techniques in ASP.Net & Explain briefly about Server Side State Management Options
Generally, Web applications are based on stateless HTTP protocol,
which doesn't hold any information about the user requests.
HTTP is stateless protocol means Server takes every request as a new request.Stateless Protocol behaviour is
Go, Get and Forget
Go --> Establish the connection to the server
Get --> Get the response from the server
Forget --> Close the connection to the server.
Http Stateless feature is an advantage for the Server. Because it will reduce the burden on webserver.If connection established to server always, many users are used the server around the world so diffenetely more burden on server.
So our aim is that we must use HTTP protocol and Server should remember user's info.This feature is came with the concept of "State Management".
Definition of StateManagement and StateManagement Types:
State Management:
This is a concept of Web Server, which remembers the user's information. OR
It holds the information about multiple user requests.
Options or Types:
1. Client Side State Management Techniques.
2 Server Side State Management Techniques.
Server side State management Options
a)Context.Items
b)Session
c)Application
d)Cache
e)Profile Properties
Server side State management
Pros
----
1)More security because data stored at server
Cons
----
1)Burden to server
a)Context.Items
If it is textbox value we can access by using Request.Form["t1"]
If it is variable we cannot access in another page
the solution is Context
-->Context object is used to maintain user information from one webpage to another webpage,when redirection is using Server.Transfer
-->Context object will be created towards client request, once response is provided it will be destroyed.
EG:-
Default.aspx
HTTP is stateless protocol means Server takes every request as a new request.Stateless Protocol behaviour is
Go, Get and Forget
Go --> Establish the connection to the server
Get --> Get the response from the server
Forget --> Close the connection to the server.
Http Stateless feature is an advantage for the Server. Because it will reduce the burden on webserver.If connection established to server always, many users are used the server around the world so diffenetely more burden on server.
So our aim is that we must use HTTP protocol and Server should remember user's info.This feature is came with the concept of "State Management".
Definition of StateManagement and StateManagement Types:
State Management:
This is a concept of Web Server, which remembers the user's information. OR
It holds the information about multiple user requests.
Options or Types:
1. Client Side State Management Techniques.
2 Server Side State Management Techniques.
Server side State management Options
a)Context.Items
b)Session
c)Application
d)Cache
e)Profile Properties
Server side State management
Pros
----
1)More security because data stored at server
Cons
----
1)Burden to server
a)Context.Items
If it is textbox value we can access by using Request.Form["t1"]
If it is variable we cannot access in another page
the solution is Context
-->Context object is used to maintain user information from one webpage to another webpage,when redirection is using Server.Transfer
-->Context object will be created towards client request, once response is provided it will be destroyed.
EG:-
Default.aspx
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) Context.Items["Test"] = "ramesh"; //Server.Transfer("Default2.aspx"); //Response.Redirect("Default2.aspx"); } protected void Button1_Click(object sender, EventArgs e) { if (Context.Items["Test"] != null) Response.Write(Context.Items["Test"]); else Response.Write("No Context"); } Default2.aspx protected void Page_Load(object sender, EventArgs e) { if (Context.Items["Test"] != null) Response.Write("Default2 Page=" + Context.Items["Test"]); else Response.Write("No Context"); }
Note:
If it is Response.Redirect instead of Server.Transfer then it will not maintain data
sol:Querystring
if it is Server.Transfer then u think about Context
if it is Respons.Redirect u think about Querystring
b)Session
Eg:
protected void Page_Load(object sender, EventArgs e) { Session["uname"] = "ramesh"; } protected void Button1_Click(object sender, EventArgs e) { if (Request.Cookies["asp.net_sessionid"] != null) { Response.Write(Request.Cookies["asp.net_sessionid"].Value); Response.Write(Request.Cookies["asp.net_sessionid"].Expires); } else Response.Write("No cookie"); }
When client makes the first request to the application Asp.Net worker process will create a block of memory unique to client, this is called "Session Memory"
This session memory will be maintained with the timeout of 20 mins by default.
To access this session memory from asp.net webpage, Microsoft is provided Session object.
1)Session.Add("Varname",value)
for eg:-
Session.Add("Uname","ramesh");
(or)
Session["Uname"] = "ramesh";
2)Session.Remove("Varname");-->It will remove variable from session memory.
3)Session.RemoveAll();-->Removes all keys and values from session-state collection.
4)Session.Clear();-->Removes all keys and values from session-state collection.
5)Session.Abandon(); -->It will kills the Session.
What is the difference between Session.Abandon() and Session.Clear()?
Ans1)Session.Abandon() destroys the session and the Session_OnEnd event is triggered.
Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear(), if you want that the user remaining in the same session (if you don't want him to relogin for example) and reset all his session specific data.
Ans2)
Session.Abandon() will end current session
Session_End will be fired and next request will fire Session_Start
Session.Clear will just clear the session data , the session is still alive
Session ID will remain same in both cases, as long as the browser is not
closed.
Ans3)
Session.Abandon() method destroys all the objects stored in a Session object and releases their resources. So Session.Abandon() destroys the current session and causes a new session to be created thus causing the Session_OnEnd and Session_OnStart events to fire.
Session.Clear() just removes all values/content from the Session Object. The session with the same key is still alive.
Ans4)
Session.Clear and Session.RemoveAll are identical; the latter just calls the former. They immediately remove all items stored in the session, but the session itself survives. Session_OnEnd does not fire.
Session.Abandon doesn't actually clear the values immediately, it just marks the session to be abandoned at the end of the current request. You can continue to read the values for the rest of the request. If you write to the session later in the request, the new value will be quietly discarded at the end of the request with no warning. Session_OnEnd fires at the end of the request, not when Abandon is called.
Ans5)
Session.Clear does not kill a Session, it clears all values.
Session.Abandon actually kills the Session.
Session Tracking:
Session tracking is the concept of identifying session belonging to the client.
This is implemented based on inmemory cookie concept.
When the session is created for the client server will assign a unique id for that session,this is called "Sessionid"
-->Sessionid will be 120-bit(ie., 15 bytes) number in the hexa decimal format
-->Server can maintain 2^120 unique sessionids towards a website.
-->This sessionid will be given to the browser in the form of inmemory cookie.
When the browser makes subsequent request it will submit sessionid to the server, based on this submitted sessionid server will identify session belonging to the client.
Session memory doesn't have any restriction interms of variables and memory size(as long as server is supported that much of memory it will take)
Cookies vs. Session
1)Cookie can store only primitive types(int,string...), we cannot store complex types(ie.,Dataset,...)
Session memory can store Objects
2)Cookies does not provide security for data(because it will store at client side)
Session memory provides security for data(because it will store at server side)
3)Processing cookies willl be faster compare to session memory.
4)Cookie max size is 4kb
but session memory doent have any limitation(as long as server is supported that much of memory it will take)
5)Number of cookies are limited(20 cookies)
No limit for number of sessions.
c)Application State:
When first client first request comes to the application asp.net worker process will allocate a block of memory common to all clients this is called "Application Memory"
This application memory doesn't have any timeout, it will be maintained till the application is running under worker process.
To access this application memory from asp.net webpage, Microsoft is provided Application object.
1)Application.Add("Varname",value)
for eg:-
Application.Add("Uname","ramesh");
(or)
Application["Uname"] = "ramesh";
2)Application.Remove("Varname");
3)Lock()
4)Unlock()
Why we need lock() and unlock()
Each client request to the webserver is considered as one thread. Webserver will provide equal processor time to all threads, In this case there is a possibility of morethan one thread manipulating same data ie., application memory data, this will provide improper results
this can be avoided with synchronization of threads
this can be implemented using lock() and unlock() methods.
Eg:
protected void lnkbtnWriteMsg_Click(object sender, EventArgs e) { Application.Lock(); Application["FlashNews"] = ".Net 5.0 is going to come into the Market"; Application.UnLock(); } protected void lnkbtnReadMsg_Click(object sender, EventArgs e) { Application.Lock(); Response.Write(Application["FlashNews"]); Application.UnLock(); }
Session and Application events:
1)Session events
a)Onstart-->It will be executed when session is created
b)Onend -->It will be executed when session is closed
2)Application events
a)Onstart-->It will be executed when website is started
b)Onend -->It will be executed when website is stopped
c)BeginRequest-->This event occurs when a client makes a request to any pages of the application. It can be useful to open connection to database for all requests.
d)EndRequest-->After a request for a page has been made, this is the last event that is called.
e)Error-->This event is used to handle all unhandled exceptions in the application. It's the best place to put your error tracking mechanism.etc.,
-->This events should be placed with in a special file called "Global.asax"[Active server application file]--> here x is silent
Global.asax
-->It is an application file, used to handle application and session level events.
-->Website supports only one global.asax file.
Eg:
---
void Application_Start(object sender, EventArgs e) { // Code that runs on application startup Application.Lock(); Application["OnlineUsers"] = 0; Application["HitCount"] = 0; Application.UnLock(); } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started Application.Lock(); Application["OnlineUsers"] = Convert.ToInt32(Application["OnlineUsers"]) + 1; Application["HitCount"] = Convert.ToInt32(Application["HitCount"]) + 1; Application.UnLock(); } void Session_End(object sender, EventArgs e) { Application.Lock(); Application["OnlineUsers"] = Convert.ToInt32(Application["OnlineUsers"]) - 1; Application.UnLock(); // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. }
e)Profile
Profile Properties allows you to store user-specific data. This feature is similar to session state,
except that the profile data is not lost when a user's session expires.
The profile-properties feature uses an ASP.NET profile,
which is stored in a persistent format and associated with an individual user.
To use profile properties, you must configure a profile provider.
ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL database.
Purpose: Used to store user specific information.
The ASP.NET profile feature allows you to store simple (scalar) values, collections and other complex types, and user-defined types.
EG:
When it comes to profile implementation the communication with database takes place two times for request processing
1)When the webpage is accessing profile properties, the total data will be retrieved from database
2)when the modifications takes place to profile data, it will be updated to database after complete processing is finished.
The client profile data will be stored into DB, by providing a unique identification based on authentication mode.
Profile implementation is recomnded, when the amount of data is small and required for less no. of pages.
Pros
1)Since the state management information is placed in profile properties,
no data is lost and is preserved even when the IIS and the application worker-process is restarted.
2)Profile properties can be persisted in multiple processes such as in a Web farm or a Web garden.
3)Profile properties can be used both in multi-computer and multi-process configurations.
Therefore, they optimize the scalability of a Web application.
Cons
1)If it is more amount of Profile data and used in more no. of pages then performance will be degraded.
(because For all client requests,It is going to retrieve entire profile data, even if it is not required.)
Differences between Session and Profile objects
The major difference between Profile and Session objects are
1. Profile object is persistent(ie., It doen't have any timeout) whereas
Session object is non-persistant.
2. Profile object uses the provider model to store information whereas
Session object uses the In Proc, Out Of Process or SQL Server Mode to store information.
3. Profile object is strongly typed whereas Session object is not strongly typed.
The similarity between them is that Each user will automatically have a profile of his own similar to Sessions where each user will have his own Session State.
Conclusion:-
ASP.NET offers a number of places to store state, both on the client and server. However, sometimes it's difficult to decide where you should put things and how to make that decision.
You choices for state management include:
1)Application - Stored on the server and shared for all users. Does not expire. Deprecated by Cache (below).
2)Cache - Stored on the server and shared for all users. Can expire.
3)Session - Stored on the server. Unique for each user. Can expire.
4)ViewState - Stored in a hidden page input (by default). Does not expire.
5)Cookies - Stored at the client. Can expire.
6)QueryString - Passed in the URL. Must be maintained with each request.
7)Context.Items - Only lasts for one request's lifetime. More.
8)Profile - Stores the data in the database. Can be used to retain user data over multiple request and session
Page submission:
Client submitting data to webserver is called "Page submission".
for eg:- login parameters,.........
2 Types
1)Postback submission: Page submitting to itself is called "Postback submission".
2)Crosspage submission: One webpage submitting to another webpage is called "Cross page submission".
Note:- Crosspage Submission will be implemented based on PostBackUrl property.
Eg:
protected void Page_Load(object sender, EventArgs e) { if (PreviousPage != null & PreviousPage.IsCrossPagePostBack) { string str = (PreviousPage.FindControl("TextBox1") as TextBox).Text; } }
Note:
Server.Transfer("Pagename",true)-->Will carry all the control values to new page.
CrosspagePostback-->will carry all the control values to new page.
Redirection between webpage through coding:-
There are 2 ways available to perform redirection through coding
1)Response.Redirect() method
2)Server.Transfer() method
Response.Redirect() vs Server.Transfer()
1)Server.Transfer supports redirection only with in website
Response.Redirect supports redirection with in website and between websites
2)Server.Tranfer will not update the browser url,
where as Response.Redirect will update the browser url
3)Server.Transfer Provides better performance over Response.Redirect
4)Response.Redirect allows followed by code execution
Server.Transfer doen't allow followed by code execution.
That's It
:)
Happy Coding
Thanks
BhaskarReddy
Labels: .Net Tutorials, Aspnet, C#, CSharp
2 Comments:
Very Good Explanation.......Thanksssssss
Great Information about state management good...
Post a Comment
Subscribe to Post Comments [Atom]
<< Home