State Management
MUHAMMAD AMIR – A M I R 4IT@ GMAI L.COM
Why we need?
Stateless HTTP Protocol:
 No information about the request
 Request created/destroyed with each post backve...
State Management in ASP.Net
State Management

Client Side!
Client Side – View State
 Mechanism that allows state values to be preserved across page postbacks
 EnableViewState prop...
Client Side – View State
 Sample:

//To Save Information in View State
ViewState.Add ("NickName", "Dolly");
//Retrieving ...
Client Side – View State
 Controls that use the view state
Client Side – Control State
 Essential for control to function properly
 It is Private viewstate for the control only
 ...
Client Side – Control State

Code Sample

public class ControlStateWebControl : Control
{
private string _strStateToSave;
...
Client Side – Hidden Fields
 Not rendered in browser
 Use to store small frequently changed data
Client Side – Hidden Fields

Code Sample

protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)|
Label1.T...
Client Side – Cookies
 Stored at client side in text file or in memory of the client browser session
 Always sent with t...
Client Side – Cookies

Code Sample

//Storing value in cookie
HttpCookie cookie = new HttpCookie("NickName");
cookie.Value...
Client Side – Query String
 Used to pass information across pages
 Information passed along with URL in clear text
Client Side – Query String
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
s...
Client Side – Summary
Client Side – Summary
State management

Recommended usage

View state

Use when you need to store small amounts of informa...
State Management

Server Side!
State Management in ASP.Net
Server Side – Application State
 Used to share information among users
 Stored in the memory of the windows process
 Gr...
Server Side – Application State
protected void Page_Load(object sender, EventArgs e)
{
int count = 0;
if (Application["Hit...
Server Side – Application State
//Stroing information in application state
lock (this)
{
Application["NickName"] = "Nipun"...
Server Side – Session State
 Place to store values that will persist across page requests
 Values stored in Session are ...
Server Side – Session State
Sample:
//Storing informaton in session state
Session["NickName"] = "ABC";
//Retrieving inform...
Server Side – Session State

Code Sample

In Process mode:
 Default mode
 Session values are stored in the web server's ...
Server Side – Session State

Code Sample

In State Server mode:
 Store data out of AppPool
 Needs to serialize objects
...
Server Side – Session State

Code Sample

In SQL Server mode:
 Highly secure and reliable

 Overhead from serialization ...
Server Side – Profile Properties
 Allows you to store user-specific data
 Unlike session state, the profile data is not ...
Server Side – Profile
Sample:
<profile>
<properties>
<add item="item name" />
</properties>
</profile>
Code Example:
<auth...
Server Side – Application State

Code Sample

State management

Recommended usage

Application state

Use when you are sto...
Links
 http://msdn.microsoft.com/en-us/library/75x4ha6s.ASPX
 http://www.c-sharpcorner.com/uploadfile/nipuntomar/state-m...
Upcoming SlideShare
Loading in …5
×

State management

805 views
750 views

Published on

ASP.Net State Management

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
805
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
55
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

State management

  1. 1. State Management MUHAMMAD AMIR – A M I R 4IT@ GMAI L.COM
  2. 2. Why we need? Stateless HTTP Protocol:  No information about the request  Request created/destroyed with each post backversion.
  3. 3. State Management in ASP.Net
  4. 4. State Management Client Side!
  5. 5. Client Side – View State  Mechanism that allows state values to be preserved across page postbacks  EnableViewState property will be set to true Advantages  No server resources are required  Simple implementation  Enhanced security features Disadvantages  Performance considerations  Device limitations  Potential security risks
  6. 6. Client Side – View State  Sample: //To Save Information in View State ViewState.Add ("NickName", "Dolly"); //Retrieving View state String strNickName = ViewState ["NickName"];  Code Example: public int SomeInteger { get { object o = ViewState["SomeInteger"]; if (o != null) return (int)o; return 0; //a default } set { ViewState["SomeInteger"] = value; } } Code Sample
  7. 7. Client Side – View State  Controls that use the view state
  8. 8. Client Side – Control State  Essential for control to function properly  It is Private viewstate for the control only  Work even when ViewState turned off
  9. 9. Client Side – Control State Code Sample public class ControlStateWebControl : Control { private string _strStateToSave; protected override void OnInit(EventArgs e) { Page.RegisterRequiresControlState(this); base.OnInit(e); } protected override object SaveControlState() { return _strStateToSave; } protected override void LoadControlState(object state) { if (state != null) { _strStateToSave = state.ToString(); } } }
  10. 10. Client Side – Hidden Fields  Not rendered in browser  Use to store small frequently changed data
  11. 11. Client Side – Hidden Fields Code Sample protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack)| Label1.Text = string.Format("Clicked {0} times", HiddenField1.Value); } protected void Button1_Click(object sender, EventArgs e) { HiddenField1.Value = (Convert.ToInt32(HiddenField1.Value) + 1).ToString(); } Label1.Text = string.Format("Clicked {0} times", HiddenField1.Value);
  12. 12. Client Side – Cookies  Stored at client side in text file or in memory of the client browser session  Always sent with the request to the web server  Read from user machine to identify user
  13. 13. Client Side – Cookies Code Sample //Storing value in cookie HttpCookie cookie = new HttpCookie("NickName"); cookie.Value = "David"; Request.Cookies.Add(cookie); //Retrieving value in cookie if (Request.Cookies.Count > 0 && Request.Cookies["NickName"] != null) lblNickName.Text = "Welcome" + Request.Cookies["NickName"].ToString(); else lblNickName.Text = "Welcome Guest";
  14. 14. Client Side – Query String  Used to pass information across pages  Information passed along with URL in clear text
  15. 15. Client Side – Query String public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { string v = Request.QueryString["param"]; if (v != null) { Response.Write("param is "); Response.Write(v); } string x = Request.QueryString["id"]; if (x != null) { Response.Write(" id detected"); } } } Code Sample
  16. 16. Client Side – Summary
  17. 17. Client Side – Summary State management Recommended usage View state Use when you need to store small amounts of information for a page that will post back to itself. Using the ViewState property provides functionality with basic security. Control state Hidden fields Cookies Use when you need to store small amounts of state information for a control between round trips to the server. Use when you need to store small amounts of information for a page that will post back to itself or to another page, and when security is not an issue. Note You can use a hidden field only on pages that are submitted to the server. Use when you need to store small amounts of information on the client and security is not an issue. Use when you are transferring small amounts of information from one page to another and security is not an issue. Query string Note You can use query strings only if you are requesting the same page, or another page via a link.
  18. 18. State Management Server Side!
  19. 19. State Management in ASP.Net
  20. 20. Server Side – Application State  Used to share information among users  Stored in the memory of the windows process  Great place to store data that changes infrequently
  21. 21. Server Side – Application State protected void Page_Load(object sender, EventArgs e) { int count = 0; if (Application["HitCounterForOrderPage"] != null) count = (int)Application["HitCounterForOrderPage"]; count++; Application["HitCounterForOrderPage"] = count; lblcounter.Text = "Page Visited: " + count.ToString() + "Times"; } //Application.Lock(); and Application.UnLock(); Code Sample
  22. 22. Server Side – Application State //Stroing information in application state lock (this) { Application["NickName"] = "Nipun"; } //Retrieving value from application state lock (this) { string str = Application["NickName"].ToString(); } Code Sample
  23. 23. Server Side – Session State  Place to store values that will persist across page requests  Values stored in Session are stored on the server  Values remain in memory until they are explicitly removed or until the Session expires
  24. 24. Server Side – Session State Sample: //Storing informaton in session state Session["NickName"] = "ABC"; //Retrieving information from session state string str = Session["NickName"]; Code Example: object sessionObject = Session["someObject"]; if (sessionObject != null) { myLabel.Text = sessionObject.ToString(); } Code Sample
  25. 25. Server Side – Session State Code Sample In Process mode:  Default mode  Session values are stored in the web server's memory (in IIS & for each IIS Server)  Values will be lost on server restart <configuration> <sessionstate mode="InProc" /> </configuration>
  26. 26. Server Side – Session State Code Sample In State Server mode:  Store data out of AppPool  Needs to serialize objects  Values will not be lost on server restart See more details <configuration> <sessionstate mode="stateserver" stateConnectionString="tcpip=127.0.0.1:42424" /> </configuration>
  27. 27. Server Side – Session State Code Sample In SQL Server mode:  Highly secure and reliable  Overhead from serialization and deserialization  Should be used when reliability is more important than performance  Setup mode in sql server by running InstallSqlState.sql Possible Path for .Net 4.0 [C:WindowsMicrosoft.NETFramework64v4.0.30319] <configuration> <sessionstate mode="sqlserver" sqlConnectionString="Data Source=(local);User ID=sa;Password=pwd" /> </configuration>
  28. 28. Server Side – Profile Properties  Allows you to store user-specific data  Unlike session state, the profile data is not lost when a user's session expires  Uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user  Each user has its own profile
  29. 29. Server Side – Profile Sample: <profile> <properties> <add item="item name" /> </properties> </profile> Code Example: <authentication mode="Windows" /> <profile> <properties> <add name="FirstName"/> <add name="LastName"/> <add name="Age"/> <add name="City"/> </properties> </profile> Code Sample
  30. 30. Server Side – Application State Code Sample State management Recommended usage Application state Use when you are storing infrequently changed, global information that is used by many users, and security is not an issue. Do not store large quantities of information in application state. Session state Use when you are storing short-lived information that is specific to an individual session and security is an issue. Do not store large quantities of information in session state. Be aware that a session-state object will be created and maintained for the lifetime of every session in your application. In applications hosting many users, this can occupy significant server resources and affect scalability. Profile properties Use when you are storing user-specific information that needs to be persisted after the user session is expired and needs to be retrieved again on subsequent visits to your application. Database support Use when you are storing large amounts of information, managing transactions, or the information must survive application and session restarts. Data mining is a concern, and security is an issue.
  31. 31. Links  http://msdn.microsoft.com/en-us/library/75x4ha6s.ASPX  http://www.c-sharpcorner.com/uploadfile/nipuntomar/state-management-in-Asp-Net/  http://www.c-sharpcorner.com/uploadfile/37db1d/hour-1-understanding-5-Asp-Net-statemanagement-techniques-in-5-hours/ with examples:  http://www.codeproject.com/Articles/492397/State-Management-in-ASP-NET-Introduction  http://msdn.microsoft.com/en-us/library/ff647327.aspx

×