Wednesday 11 September 2013

9 Ways to Manage State in ASP.NET

Managing State in ASP.NET 

  1. Session State.

  2. Application State.

  3. HttpContext / Request State.

  4. View State.

  5. Control State.

  6. Cache.

  7. Profile.

  8. Cookies.

  9. Query Strings.  

     

    1. Session State

    The most commonly used and understood state  is the  old Session object. Objects you stored here are persisted on the server, and available between requests made by the same user.
  • Security isn’t too much of an issue, because the objects are never sent down to the client. You do need to think about security
  • Depending on how ASP.NET is configured, the objects could get pushed back to a SQL database or an ASP.NET state server which means they’ll need to be serializable. 
  • If you’re using the default in-proc storage mode you need to think carefully about the amount of RAM potentially getting used up here. 
  • You might lose the session on every request if the user has cookies disabled, and you haven’t enabled cookie-less session support, however that’s incredibly rare in this day and age.
Usage is as simple as:
Session["key"] = Object
Session["key"] = “Hai ”;--------Maintaining Data Per User

     

2. Application State

Application state is also very commonly used and understood because it  is using from the ASP days. It is very similar to session state, however it is a single state bag shared by all users across all requests for the life of the application.
  • Security isn’t really an issue at all here because once again, the objects are never sent over the wire to the client. 
  • Everything in the bag is shared by everyone, so don’t put anything user specific here.
  • Anything you put here will hang around in memory until the application is recycled, or you explicitly remove it so be conscious of what you’re storing in to memory.
Generally using Cache is a better solution – as described below, it too is shared across all requests, but it does a very good job of managing its content life cycle.

Usage is a simple as:
Application["key"] = “Hello”;--------Maintaining Data across the Application


3. HttpContext / Request State

Next we have HttpContext.Current.Items.  I generally call it “Request State”. I think that name clearly indicates its longevity – that is, only for the length of the request.
It is designed for passing data between HTTP modules and HTTP handlers. In most applications you wouldn’t use this state bag, but its useful to know that it exists. Also, because it doesn’t get persisted anywhere you don’t need to care about serialization at all.

Usage is as simple as:
HttpContext.Current.Items.Add(“key”, “hello”);

4. View State

View state is used to store information in a page between requests. For example, I might pull some data into my page the first time it renders, but when a user triggers a postback I want to be able to reuse this same data.
  • View state gets stored into the page, and if you save the wrong content into it you’ll rapidly be in for some big pages. Have a think about how long that page took to load!
  • It’s generally used for controls to be able to remember things between requests, so that they can rebuild themselves after a postback. It’s not very often that I see developers using view state directly, but there are some legitimate reasons for doing so.
  • Each control has its own isolated view state bag. Remember that pages and master pages each inherit from Control, so they have their own isolated bags too. View state is meant to support the internal plumbing of a control, and thus if you find that the bags being isolated is an issue for you then it’s a pretty good indicator that you’ve taken the wrong approach with your architecture.
  • It can be controlled on a very granular level – right down to enabling or disabling it per control. There’s an EnableViewState property on every server control, every page (in the page directive at the top) every master page (also in the directive at the top), and an application wide setting in web.config. These are all on my default, but the more places you can disable it in your app, the better.
Usage is as simple as:
ViewState["key"] = “Hai ”;------Maintaining data at page level.

5. Control State

Control state is somewhat similar to view state, except that you can’t turn it off.
The idea here is that some controls need to persist values across requests no matter what (for example, if it’s hard to get the same data a second time ’round).

 It was only added in ASP.NET 2.0 . Some controls will break completely if you do a postback without view state having being enabled.even the most personal of operations must go via a server side event, so you’ll always do a postback – right? Wrong.
If you’re a control developer, please be very very conscious about your usage of control state.

6. Cache

Just like application, it’s shared between all requests and all users for the entire life of your application.
What’s cool about Cache is that it actually manages the lifecycle of its contents rather than just letting them linger around in memory for ever ‘n ever. It facilitates this in a number of ways:
  • absolute expiry (“forget this entry 30 minutes from now”)
  • sliding expiry (“forget this entry if it’s not used for more than 8 minutes”)
  • dependencies (“forget this entry when file X changes”)
Even cooler yet, you can:
  • Combine all of these great features to have rules like “forget this entry if it’s not used for more than 8 minutes, or if it gets to being more than 20 minutes after we loaded the data, or if the file we loaded it from changes”.
  • Handle an event that tells you when something has been invalidated and thus is about to be removed from the cache. This event it is per cache item, so you subscribe to it when you create the item.
  • Set priorities per item so that it can groom the lower priority items from memory first, as memory is needed.
  • With .NET 2.0, you can point a dependency at SQL so when a particular table is updated the cache automatically gets invalidated. If you’re targeting SQL 2005 it maintains this very intelligently through the SQL Service Broker. For SQL 2000 it does some timestamp polling, which is still pretty efficient but not quite as reactive.
Even with all this functionality, it’s still  simple to use:
Check out the overloads available on Cache.Items.Add();

7. Profile

I don’t really think of profile as state. It’s like calling your database “state” – it might technically be state.

The idea here is that you can store personalization data against a user’s profile object in ASP.NET. The built in framework does a nice job of remembering profiles for anonymous users as well as authenticated users, as well as other  things like migrating an anonymous user’s state when they signup, etc.

By default you’d run the SQL script they give you create a few tables, then just point it at a SQL database and let the framework handle the magic.

I don’t like doing this because it stores all of the profile content in serialized binary objects making them totally opaque (not clear) in SQL and non-queryable. I like the idea of being able to query out data like which theme users prefer most. There’s a legitimate business value in being able to do so, as trivial as it may sound.

This problem is relatively easily resolved by making your own provider. You still get all the syntactic and IDE sugar that comes with ASP.NET Profiles, but you get to take control of the storage.

8. Cookies

Cookies are how the web handles state, and can often be quite useful to interact with directly from ASP.NET. ASP.NET uses cookies itself to store values like the session ID (used for session state) and authentication tokens. That doesn’t stop us from using the Request.Cookies and Response.Cookies collections ourselves though.
  • Security is definitely an issue because cookies are stored on the client, and thus can be very easily read and tampered with (they are nothing more than text files).
  • Beware the cookies can often be access from JavaScript too, which means that if you’re hosting 3rd party script then it could steal cookie contents directly on the client = major XSS risk. To avoid this, you can flag your cookies as “HTTP only”.
  • They are uploaded to the server with every request, so don’t go sticking anything of substantial size in there. Typically you will just store an id or a token in the cookie, and the actual content back on the server.
  • Cookies can live for months or even years on a user’s machine (assuming they don’t explicitly clear them) meaning they’re a great way of persisting things like shopping carts between user visits.
I’m glad the ASP.NET team gave us access as raw as they did, but it also means that you need to have an understanding of how cookies work before you use them. As much as it might seem, you can’t just jump in and use them straight away.

9. Query Strings

The query string is about as simple as you can get for state management. It lets you pass state from one page, to another, even between websites.
I’m sure you’re all familiar with query strings on the end of URLs like ShowProducts.aspx?customerId=222.

Usage is as simple as:
string customerId= Request.QueryString["customerId"];

    No comments:

    Post a Comment