Ap.net State Management

  • Uploaded by: api-19796528
  • 0
  • 0
  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Ap.net State Management as PDF for free.

More details

  • Words: 2,490
  • Pages: 39
State Management By SRIRAM. B

State Management Overview 

State Management



Server Side Options





Application State



Session State



Profile Properties



Database Support

Client Side Options 

View State



Control State



Hidden Field



Cookie



Query String

State Management 

Describes how to store information between page requests.



As is true for any HTTP-based technology, Web Forms pages are stateless, which means that they do not automatically indicate whether the requests in a sequence are all from the same client or even whether a single browser instance is still actively viewing a page or site.



Furthermore, pages are destroyed and re-created with each round trip to the server; therefore, page information will not exist beyond the life cycle of a single page.

Server Side Options

Server Side Options 

Server-side options for storing page information typically have higher security than client-side options, but they can use more Web server resources, which can lead to scalability issues when the size of the information store is large. ASP.NET provides several options to implement server-side state management.



The following are the server-side state management options that ASP.NET supports:



Application state



Session state



Profile properties



Database support

Application State 

ASP.NET allows you to save values using application state — which is an instance of the HttpApplicationState class — for each active Web application.



Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages.



Application state is stored in a key/value dictionary that is created during each request to a specific URL. You can add your application-specific information to this structure to store it between page requests.



Once you add your application-specific information to application state, the server manages it.

Application State 



Advantages 

Simple Implementation



Application Scope

Dis-Advantages 

You cannot rely on application state to store unique values or update global counters in Web-garden and Web-farm server configurations.



Limited Durability of data



Resource Requirements

Application State 

To Store the application variable in config file Application[“myapp”] = “Welcome to ASP.NET”;



For accesing the application variable in web form String s = Application[“myapp”].ToString(); Label1.Text = s;

Session State 

ASP.NET allows you to save values by using session state — which is an instance of the HttpSessionState class — for each active Web-application session



Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session will have a different session state. In addition, if a user leaves your application and then returns later, the second user session will have a different session state from the first.



Session state is structured as a key/value dictionary for storing sessionspecific information that needs to be maintained between server round trips and between requests for pages.

Session State.. 



You can use session state to accomplish the following tasks: Uniquely identify browser or client-device requests and map them to an individual session instance on the server.



Store session-specific data on the server for use across multiple browser or client-device requests within the same session.



Raise appropriate session management events. In addition, you can write application code leveraging these events.



Once you add your application-specific information to session state, the server manages this object. Depending on which options you specify, session information can be stored in cookies, on an out-of-process server, or on a computer running Microsoft SQL Server

Session State 

Session Identifier –> SessionID



Session Events –> Session_OnStart, Session_OnEnd



Session Methods –> Session.Abandon(), Session.TimeOut()



Advantages





Simple Implementation



Session Specific events



Data Persistance



Cookieless Support

Dis-Advantages 

Performance Decreases -> Session-state variables that contain blocks of information, such as large datasets, can adversely affect Web-server performance as server load increases.

Session Mode 

InProc mode, which stores session state in memory on the Web server. This is the default.



StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. <sessionState mode="StateServer" stateConnectionString="tcpip=SampleStateServer:42424" cookieless="false" timeout="20"/>



Custom mode, which enables you to specify a custom storage provider.



Off mode, which disables session state.

Session Mode 

SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. <system.web> <sessionState mode="SQLServer" sqlConnectionString="Integrated Security=SSPI;data source=SampleSqlServer;" />



The command creates a database named ASP State on a SQL Server instance named "SampleSqlServer" and specifies that session data is also stored in the ASPState database: aspnet_regsql.exe -S SampleSqlServer -E -ssadd -sstype p

Diff. Between ASP Session & ASP.NET Session 

ASP session state is dependent on IIS process, so if IIS restarts ASP session variables are recycled.



ASP.NET session can be independent of hosting environment thus ASP.NET session can be maintained even if IIS reboots.



ASP session state has no inherent solution to work with web farms.



ASP.NET session can be stored in State Server & SQL Server which can support multiple server.



ASP session will functions only when the browser supports cookies.



ASP.NET session can be used with browser side cookies or independent of it.

Session State.. 

To create a session in the web form Session[“id”] = TextBox1.Text;



For accesing the session variable in another web form Label1.Text = Session[“id”].ToString();

Profile Properties 

ASP.NET provides a feature called profile properties, which allows you to store user-specific data.



It is similar to session state, except that unlike session state, 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.



The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database.

Profile Properties.. 



Advantages 

Data Persistance



Platform Scalability



Extensibility

Dis-Advantages 

Profile properties are generally slower than using session state because instead of storing data in memory, the data is persisted to a data store.



To use profile properties, you must not only configure a profile provider, but you must pre-configure all of the profile properties that you want to store.



Data maintenance

Database Support 

To use database support to maintain state on your Web site. Typically, database support is used in conjunction with cookies or session state. For example, it is common for an e-commerce Web site to maintain state information by using a relational database for the following reasons: 

Security



Personalization



Consistency



Data mining

Database Support .. 



Advantages 

Security



Storage Capacity



Data Persistance



Wide Spread



Accessibility



Robustness & Data Integrity

Dis-Advantages 

Using a database to support state management requires that the hardware and software configurations be more complex..



Poor construction of the relational data model can lead to scalability issues. Also, leveraging too many queries to the database can adversely affect server performance.

Client Side Options

Client Side Options 

Storing page information using client-side options doesn't use server resources. These options typically have minimal security but fast server performance because the demand on server resources is modest. However, because you must send information to the client for it to be stored, there is a practical limit on how much information you can store this way.



The following are the client-side state management options that ASP.NET supports:

• View state • Control state • Hidden fields • Cookies • Query strings

View State 

The ViewState property provides a dictionary object for retaining values between multiple requests for the same page.



This is the default method that the page uses to preserve page and control property values between round trips.



When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.

View State.. 



Advantages 

No server resources reqd. & Simplicity



States are retained automatically



Values of the view states are hashed, compressed and encoded, thus representing a higher state of security than hidden fields.



View state is good for caching data in web form configurations because the data is cached on the client.

Dis-Advantages 

Performance :- Page loading and Posting performance decreases when large values are stored because the view state is stored in the page.



Security Risks :- The view state is stored in one or more hidden fields on the page. Although view state stores data in a hashed format, it can still be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue.

Control State 



Sometimes you need to store control-state data in order for a control to work properly. For example, if you have written a custom control that has different tabs that show different information, in order for that control to work as expected, the control needs to know which tab is selected between round trips. The ViewState property can be used for this purpose, but view state can be turned off at a page level by developers, effectively breaking your control. To solve this, the ASP.NET page framework exposes a feature in ASP.NET called control state.



The ControlState property allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property.

Control State.. 



Advantages 

No server resources are required



Because control state cannot be turned off like view state, control state is a more reliable method for managing the state of controls.



Custom adapters can be written to control how and where control-state data is stored. versatile

Dis-Advantages 

Some programming is required

Hidden Field 

ASP.NET allows you to store information in a HiddenField control, which renders as a standard HTML hidden field.



A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls.



A hidden field acts as a repository for any page-specific information that you want to store directly in the page.



A HiddenField control stores a single variable in its Value property and must be explicitly added to the page.

Hidden Field.. 



Advantages 

No server resources reqd.



All browsers support hidden field



Simple to implement



As data is cached on client side they work with web forms

Dis-Advantages 

They can be tampering by creating a security hole



Page performance decreases if you store large data, as the data are stored in pages itself.



Hidden Fields are stored as single valued.

Cookie 



A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.



You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value.



A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application.

Cookie 



Advantages 

No server resources are requiered as they stored in client.



They are light weight and easy to use.

Dis-Advantages 

Size Limitations : Most browsers place a 4096-byte limit on the size of a cookie, although support for 8192-byte cookies is becoming more common in newer browser and client-device versions.



Some users disable their browser or client device's ability to receive cookies, thereby limiting this functionality.



Cookies are subject to tampering by creating a security hole



Cookies can expire thus leading to in-consistency.

Cookie Methods 

To set a Cookie HttpCookie MyCookie = new HttpCookie("LastVisit"); DateTime now = DateTime.Now; MyCookie.Value = now.ToString(); MyCookie.Expires = now.AddHours(1); Response.Cookies.Add(MyCookie);



To write a cookie by creating an instance of the HttpCookie object HttpCookie myCookie = new HttpCookie("UserSettings"); myCookie["Font"] = "Arial"; myCookie["Color"] = "Blue"; myCookie.Expires = DateTime.Now.AddDays(1d); Response.Cookies.Add(myCookie);

How to set / get a Cookie 

To set a cookie HttpCookie myCookie = new HttpCookie("myCookie1"); myCookie.Value=TextBox1.Text; Response.Cookies.Add(myCookie); Response.Write(myCookie.Name); Response.Write(myCookie.Value.Length); Response.Write(myCookie.Expires);



To get a Cookie Label1.Text = Request.Cookies[“myCookie1”].Value;

Query String 

A query string is information that is appended to the end of a page URL. http://www.contoso.com/listwidgets.aspx? category=basic&price=100 In the URL path above, the query string starts with a question mark (?) and includes two attribute/value pairs, one called "category" and the other called "price."



Query strings provide a simple but limited way to maintain state information. For example, they are an easy way to pass information from one page to another, such as passing a product number from one page to another page where it will be processed.

Query String.. 



Advantages 

No server resources are required



All browsers support query strings

Dis-Advantages 

Directly Visible to the users thus leading the security problems



Most Browsers & Client devices impose a 255 character limit on URL length.

Query String 

To Store the application variable in config file Response.Redirect(“ProductDetails.aspx? id=”+TextBox1.Text);



For accesing the application variable in web form String q = Request.QueryString[“id”].ToString(); Response.Write(q);

Diff. Between Response.Redirect & Server.Transfer 



Response.Redirect 

Will navigate to a particular page and will not get any value



Works with any server



No Round Trip



Url information passed during transfer

Server.Transfer 

Will fetch the value from previous form



Works within the server



Round Trip



No Url information passed during transfer

Demo

Session Ends

Exercise

Relax

Related Documents

State Management
June 2020 3
State
May 2020 26
State
June 2020 21
State
July 2020 19