Showing posts with label ASP.NET. Show all posts
Showing posts with label ASP.NET. Show all posts

ASP.NET Page Life Cycle

When an ASP.NET application is executed, the web page goes through a life cycle in which it performs a series of processing steps. When a web page is requested, it is loaded into the Web Server memory, processed and sent to the web browser. Then it (the object) is unloaded from the memory. At each of these steps, methods and events are available, ready to be overridden according to the need of the application.

The Page class creates a control tree of all the controls on the page. All the components on the page, except the directives are part of this control tree. 

ASP.NET Page Life Cycle Phases
  • Initialization
  • Instantiation of controls on the web page
  • Restoration and Maintenance of state
  • Execution of the Event Handler code
  • Page Rendering

ASP.NET Page Life Cycle Stages
  • Page Request – The ASP.NET page life cycle (PLC) begins after the page is requested by a user. ASP.NET then determines whether the web page needs to be parsed and compiled, or a cached version of the page can be sent in response without running the page.
  • Start – The page properties such as Request and Response are set at the Start stage. It is determined whether the request is a postback (old request) or a new request and IsPostBack property of the Page is set accordingly. The UICulture property of the Page is also set at this stage.

    Events
      a) PreInit – Raised after the Start stage is complete and before the Initialization stage begins 
  • Initialization – The controls on the web page are available during page initialization, and UniqueID property of each control is set. If applicable, master page and themes are also applied to the page during initialization. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

    Events
      a) InitRaised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.
b) InitComplete – Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on.
View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.
  • Load – During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

    Events
      a) PreLoad – Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance. 
       
      b) Load – The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.
  • Postback event handlingIf the request is a postback, the event handlers of the controls are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page. (There is an exception to this sequence: the handler for the event that caused validation is called after validation.)

    Events
      a) Control Events – These events should be used to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
      In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.

      b) Load Complete – Raised at the end of the event-handling stage.

      c) PreRender – Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. To do this, the Page object calls EnsureChildControls for each control and for the page.
      The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.

      d) PreRender Complete – Raised after each data bound control whose DataSourceID property is set calls its DataBind method.

      e) SaveStateComplete - Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
  • RenderingThe view state is saved for the page and all controls before rendering. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.

    Events
      a) Render - This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser. A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code. 
       
  • Unload - The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.

    Events
      a) Unload - Raised for each control and then for the page. During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception

ASP.NET HttpHandlers – Are they really required?

ASP.NET HttpHandler is a process that runs in response to a request that is made to an ASP.NET Web application. Almost everything we do in an HttpHandler, can be done in a normal .aspx page. So, why do we need HttpHandlers? Are they really required?

Given below is the explanation of why HttpHandlers are really required:
  1. Reusability & Portability – HttpHandlers are more reusable and portable than normal .aspx pages. Since there are no visual elements in an HttpHandler, they can be easily placed into their own assembly and reused from project to project.
  2. HttpHandlers are relatively less expensive than the PageHandler. A page goes through a set of events to be processed at the server (such as onInit, onLoad, etc.), ViewState and postbacks or simply the complete Page Life Cycle. When you really have nothing to do with the complete page life cycle (like displaying images), HttpHandlers are very useful.

Handlers in ASP.NET

Handler is an agent of communication or a medium which is responsible for communication in the absence of the actual user. Technically, a Handler is a class which is responsible for Instantiation of a class i.e; allocation of memory.

Console applications or Windows applications do not have handlers. We declare a class and create an object of that class in the Main() method. We as a developer are solely responsible for handling the class – specifically - instantiation of the class.

However, Web applications have handlers. In GUI Web Applications we never create an object of the “_default” page which inherits the Page class.
In Web Services, the Web Service class is never instantiated.
In WCF, the Service class, which inherits the IService Interface is never instantiated.

Now comes the question – Who instantiates the above mentioned classes?

Behind the scene, the Handler is responsible for instantiation of the above mentioned classes. ASP.NET maps HTTP requests to HTTP handlers based on the extension of the requested file (type of file). Each HTTP handler can process individual HTTP URLs or groups of URL extensions in an application. ASP.NET includes several built-in HTTP handlers:

a)    ASP.NET – System.Web.UI.PageHandlerFactory
b)    Web Service – System.Web.Services.Protocols.WebServiceHandlerFactory
c)    WCF – System.ServiceModel.Activation.ServiceHttpHandlerFactory

There are different drivers for different protocols. The driver or API of the protocol (ex – http.sys) has to have the ability to differentiate and resolve requests.
 
.sys files are the drivers for protocols. http.sys file is a driver or API or listener for the HTTP protocol. You can say that HTTP is abstraction, while http.sys is encapsulation. http.sys file handles the request and response in HTTP. The http.sys file is located in C:\Windows\System32\drivers\ folder.

When a request arrives on the server, the drivers for the protocols (.sys files) handles that request and forwards that request to a particular handler according to the extensions.

Differentiate between Server.Transfer() & Response.Redirect()

Both Server.Transfer and Response.Redirect are ASP.NET objects and are used for navigation between web-pages. However, there are noticeable differences between these two techniques:

Response.Redirect()
  • Response.Redirect() redirects the user to another web-page which may or may not be on the same server. It can redirect the user to an external website on a different server.
  • Response.Redirect() updates the address bar and adds the updated URL to the browser history. User can click back on the browser to navigate to the previous page.
  • Response.Redirect() terminates the request with HTTP 302 status and client-side roundtrip. Client then navigates to the new address and the browser address bar and history updates. The client pays the cost of additional round-trips to the server on each request.
  • Form variables are are not transferred upon a call to Response.Redirect().

Server.Transfer()
  • Server.Transfer() quits current execution of the web-page and redirects the user to another web-page on the same server. It cannot send the user to an external website on a different server.
  • Server.Transfer() keeps the URL unchanged in the address bar. It happens entirely on the server side and the client browser’s address bar remains constant. User cannot click on back button on the browser to navigate to the previous page
  • Server.Transfer() reduces the server request and conserves server resources. It simply changes the focus on the Web Server and transfers the request. With Server.Transfer() there are less number of HTTP requests, which eases pressure on the Web Server and makes the application execute faster.
  • Developer can transfer Query Strings and form variables with a little bug-bashing. The Server.Transfer() method has a second parameter – preserveForm. If this is set to True, the existing query string and form variables will be available to the transferred page. Ex – Server.Transfer(“webpage2”, True);

Differentiate between web.config, app.config and machine.config files

web.config file

  • web.config is used for ASP.NET Web Projects / Web Services. web.config by default has several configurations required for the web application. It is also called Application Level Configuration File and inherits setting from the machine.config file.
  • web.config is parsed at runtime, so if you edit the web.config file, the web application will automatically load the changes in the config file.
  • web.config file is automatically generated when new web application created.
  • You can have more than one web.config file in your application. Specifically, you can have a web.config for each folder under your web application.
  • The web.config file is required for ASP.NET webpages.

app.config file

  • app.config is used for Windows Forms, Windows Services, Console Apps and WPF applications.
  • app.config is parsed at compile time, so if you edit the app.config file, you have to restart the application. At compile time a copy of the app.config file is taken, renamed to [output].config and moved to the build folder. This copy can then be modified, and your modifications will be read each time the application/service is started.
  • app.config is not added automatically to an application. You can go to the solution explorer, select 'Add new item' and add the 'Application Configuration File'.
  • There is always one app.config file in a window application.
  • The app.config file is optional in an application and doesn't have to be used when writing desktop applications.

machine.config file


  • machine.config file is automatically installed on your system when you install Visual Studio.Net. This is also called Machine Level Configuration File. Only one machine.config file exists on a server, and is at the highest level in the configuration hierarchy.
  • The settings of machine.config file are applied to all the web applications residing on the server.
  • The machine.config file is overridden by the web.config file.
  • Without the machine.config file, application can not be executed.

The global.asax file in ASP.NET

The global.asax file in ASP.NET as an application file, which is optional and allows us to write code that response to global application events raised by ASP.NET or by HttpModules. These events fire at various points during the lifetime of a web application, including when the application domain is first created.

The global.asax file resides in the root directory of an ASP.NET application. At run time, global.asax is parsed and compiled into a dynamically generated .NET Framework class derived from the HttpApplication base class.

The global.asax file looks very similar to a normal .aspx file. However, instead of containing HTML or ASP.NET tags, it contains event handlers that response to application events. Each ASP.NET application can have only one global.asax file. Once you place it in the appropriate website directory, ASP.NET recognizes it and uses it automatically.

The ASP.NET global.asax file can coexist with the ASP global.asa file.

Basic Application Events

S. No.
Event Handling Method
Description
1
Application_Start()
Application_Start() event occurs when the application starts, which is the first time it receives a request from any user. It doesn’t occur on subsequent requests. This event is commonly used to create or cache some initial information that will be reused later.
2
Application_End()
Application_End() event occurs when the application is shutting down, generally because the web server has restarted. You can insert cleanup code here.
3
Application_BeginRequest()
Application_BeginRequest() event occurs with each request the application receives, just before the page code is executed.
4
Application_EndRequest()
Application_EndRequest() event occurs with each request the application receives, just after the page code is executed.
5
Session_Start()
Session_Start() event occurs whenever a new user request is received and a session is started.
6
Session_End()
Session_End() event occurs when a session times out or is programmatically ended. This event is only raised if you are using in-process session state storage (the InProc mode, not the StateServer or SQLServer modes ).
7
Application_Error()
Application_Error() event occurs in response to an un-handled error.

IsPost Property in ASP.NET & HTTP GET and POST Methods

The HTTP protocol (used for web pages) supports a very limited number of methods (verbs) that are used to make requests to the server. The two most common ones are GET (which is used to read a page), and POST (which is used to submit a page). In general, the first time a user requests a page, the page is requested using GET. If the user fills in a form and then clicks a submit button, the browser makes a POST request to the server.

In web programming, it's often useful to know whether a page is being requested as a GET or as a POST so that you know how to process the page. In ASP.NET Web Pages, you can use the IsPost property to see whether a request is a GET or a POST. If the request is a POST, the IsPost property will return true, and you can do things like read the values of text boxes on a form.

Page Life Cycle - Guess the correct answer

In which stage of general page life cycle, 'IsPostBack' property is set?

1) Page Request
2) Start
3) Load
4) Validation
5) Rendering


Answer: Option 2: Start

Explanation: In the Start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property.

External Link: Page Life Cycle in ASP.NET

List ASP.NET Page Life Cycle events

Page Event
Controls Initialized
Is ViewState Enabled
 When is this Event Raised
Logic

PreInit

No No After the start stage is complete and before the initialization stage begins This event can be used for the following:
1) Check the IsPostBack property. The IsCallback and IsCrossPagePostBack properties are also set at this time.
2) Create or re-create dynamic controls.
3) Set a master page dynamically.
4) Set the Theme property dynamically.
5) Read or set profile property values.
Note: If the request is a postback, the values of the controls have not yet been restored from view state.

Init

Not guaranteed No After all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page. This event can be used to read or initialize control properties.

InitComplete

Not guaranteed Yes At the end of the page’s initialization stage.
Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection.
This event can be used to make changes to view state that you want to make sure are persisted after the next postback.

LoadViewState

Not guaranteed Yes This event happens only at postbacks
The Viewstate which has been saved in the __VIEWSTATE during the previous page visit (via the SaveViewState event) is loaded and then populated into the control hierarchy.

LoadPostbackdata

Not guaranteed Yes This event happens only at postbacks
During this event, the posted form data is loaded into the appropriate controls.

PreLoad

Yes Yes After the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.

Load

Yes Yes
The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.
The OnLoad event can be used to set control properties and database connections.

Control events

Yes Yes Raised at the end of the event-handling stage.
These events can be used to handle specific control events, such as a Button control’s Click event or a TextBox control’s TextChanged event.
Note: In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.

LoadComplete

Yes Yes Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls.This event can be used for tasks that require that all other controls on the page be loaded.

PreRender

Yes Yes

The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.

 The event can be used to make final changes to the contents of the page or its controls before the rendering stage begins.

PreRenderComplete

Yes Yes
Raised after each data bound control whose DataSourceID property is set calls its DataBind method.

SaveStateComplete

Yes Yes
Raised after view state and control state have been saved for the page and for all controls.
Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.

Render

Yes Yes This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control’s markup to send to the browser.


If you create a custom control, you typically override this method to output the control’s markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method.
We do not need to explicitly render the control in code because a user control automatically incorporates rendering.

Unload

Yes Yes Raised for each control and then for the page.
This event can be used to do final cleanup for specific controls, such as closing control-specific database connections.
Note: During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

State Management in ASP.Net

Web applications are based on stateless HTTP protocol which does not retain any information about user requests. In typical client and server communication using HTTP protocol, page is created each time the page is requested.

We can classify state management techniques as client side state management and server side state management, each of which has its own pros and cons.

Client Side State Management:


Various client side state management options in ASP.NET are Cookies, QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0). 

Cookie: 

A cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user.

Example: This example makes use of cookies to customize web page.

if (Request.Cookies["UId"] != null)
    lbMessage.text = "Mr/Mrs" + Request.Cookies["UId"].Value + ", Welcome!";
else
    lbMessage.text = "Hi, welcome!";


Client's information can be stored as given below:

Response.Cookies["UId"].Value=username;

Advantages:
  • Simplicity
Disadvantages:
  • Cookies can be disabled on user browsers
  • Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
  • Inappropriate for sensitive data

Hidden fields:

Hidden fields are not rendered by the browser and used to store data at the page level. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. We can use hidden fields in ASP.NET pages using following syntax:

protected System.Web.UI.HtmlControls.HtmlInputHidden HiddenField;
 
//to assign a value to Hidden field
HiddenField.Value="This is a hidden field";
//to retrieve a value
string str=HiddenField.Value;

Advantages:
  • Simple to implement for a page specific data
  • Can store small amount of data so they take less size.
Disadvantages:
  • Inappropriate for sensitive data
  • Hidden field values can be intercepted(clearly visible) when passed over a network

View State:

View State is a built in feature in web controls to persist data between page post backs. It can be used to store state information for a single user. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true

View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. Disable View State for all the controls for which you don't need state, to reduce performance penalty (Data grid usually doesn't need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive. View state data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.

// Add item to ViewState
ViewState["viewstate"]  = viewstateValue;
 
//Reading items from ViewState
Response.Write(ViewState["viewstate"]);

Advantages:
  • Simple for page level data
  • Encrypted 
  • Can be set at the control level
Disadvantages:
  • Overhead in encoding View State values
  • Makes a page heavy

Query strings:

Query strings are usually used to send information from one page to another page along with URL in clear text. We can only pass smaller amounts of data using query strings. Most browsers impose a limit of 255 characters on URL length. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncodeQuery strings can be used using the following syntax:

string prodId;
prodId=Request.QueryString["prodId"];
          
Advantages:
  • Simple to Implement
Disadvantages:
  • Human Readable 
  • Client browser limit on URL length
  • Cross paging functionality makes it redundant 
  • Easily modified by end user

Control State:

Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled. 

For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behaviour across post backs. Grid View is in no way affected when we disable View State for the Grid View or entire page.


Server Side State Management:


Server Side State Management maintains state information on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.

Application State:

Application State is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.
In classic ASP, application object is used to store connection strings. It's a great place to store data which does not changes frequently. We should write to application variable only in Application_Onstart event (global.asax) or Application.Lock event to avoid data conflicts. Below code sample gives idea:

Application.Lock();
Application["testData"]="testData";
Application.UnLock();

Session State:

Session State is used to store state specific information per client basis. Session data persists for the duration of user session. Session state can be configured using the <sessionState> section in the application's web.config file. 

Configuration information:

<sessionState mode = <"inproc" | "sqlserver" | "stateserver">
 cookieless = <"true" | "false">
 timeout = <positive integer indicating the session timeout in minutes>
 sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
 server = <The server name that is only required when the mode is State Server>
 port = <The
port number that is only required when the mode is State Server>

      
Mode:
This setting supports three options. They are InProc, SQLServer, and State Server.

Cookie less:

This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.

Timeout:
This indicates the Session timeout value in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes.

SqlConnectionString:

This identifies the database connection string that names the database used for mode SQLServer.

Server:

In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.

Port:
This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.


You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.

Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability:
  • In process mode (in-memory) - State information is stored in memory of web server.
  • Out-of-process mode - Session state is held in a process called aspnet_state.exe that runs as a windows service.
  • Database mode - session state is maintained on a SQL Server database.
In process mode:
This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server.

Configuration information:
<sessionState mode="Inproc"
 sqlConnectionString="data source=server;user id=freelance;password=freelance"
 cookieless="false" timeout="20" />

Advantages:
  • Fastest mode 
  • Simple configuration
Disadvantages:
  • Session data will be lost if the worker process or application domain recycles
  • Not ideal for web gardens and web farms
Out-of-process Session mode (State Server mode):
This mode is ideal for scalable and highly available applications. Session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. We can invoke state service using services MMC snap-in or by running following net command from command line.

Net start aspnet_state

Configuration information:

<sessionState mode="StateServer"
 StateConnectionString="tcpip=127.0.0.1:42424"
 sqlConnectionString="data source=127.0.0.1;user id=freelance; password=freelance"
 cookieless="false" timeout="20"/>  

                                                         
Advantages:
  • Supports web farm and web garden configuration.
  • Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state
Disadvantages:
  • Out-of-process mode provides slower access compared to In process.
  • Requires serializing data.  
SQL-Backed Session state:
ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.

SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory
 C:\<windows>\microsoft.net\framework\<version>. Running this utility will create a database which will manage the session state.


Configuration Information:
<sessionState mode="SQLServer"
  sqlConnectionString="data source=server;user id=freelance;password=freelance"
  cookieless="false" timeout="20" />

Advantages:
  • Supports web farm and web garden configuration
  • Session state is persisted across application domain recycles and even IIS restarts when session is maintained on different server.
Disadvantages:
  • Requires serialization of objects

Advantages of Client – Side State Management:

1. Better Scalability: With server-side state management, each client that connects to the Web server consumes memory on the Web server. If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.

2. Supports multiple Web servers: With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client’s state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access).

Advantages of Server – Side State Management:

1. Better security: Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, you should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status.

2. Reduced bandwidth: If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server.