Tuesday 22 October 2013

Memory Management in asp.net

The article/code snippet includes various points that should be given time for effective memory management. It does not give solutions but gives an inside into what options are there.

  1. Effective use of Caching.
    The main reasons for caching are performance related. Memory in ASP.NET is still a very limited resource. Do not waste it by caching anything more than a couple of minutes unless it is very expensive to regenerate. Various types of caching are:
    • Page Level Output Caching: : This keeps a copy of the HTML that was sent in response to a request in memory. Subsequent requests are then sent the cached output until the cache expires. Thus round way trips are saved to memory and response time improves.
    • Fragment caching, User Control Output Caching: There are situation where caching the entire page is not feasible. Only certain parts of the page are customized for the user. In such scenarios, fragment caching is used. Menus and other layout elements, especially ones that are dynamically generated from a data source, should be cached with this technique.


  2. Type Sizing
    Memory usage ultimately depends on the types defined and used by the assemblies in your program. Here the important point is what types to be used since, the bytes occupied by .NET data types is fixed. bool takes 1 byte, double 8, decimal 16, Int32 takes 2 byte, etc... So nothing much can be done about these. The concern is structures, references. The size of a reference type is the size of its fields rounded up to the next 4-byte boundary, plus 8 bytes of overhead. So a reference type will always occupy at least 12 bytes. A Structure size is computed as the sum of the sizes of its fields but is problematic if you need to store a reference to the type, since frequent boxing can memory and CPU cycles.
  3. Pooling
    Once an application is up and running, memory utilization is affected by the number and size of objects the system requires. Object pooling reduces the number of allocations, and therefore the number of garbage collections, required by an application. Pooling is quite simple: an object is reused instead of allowing it to be reclaimed by the garbage collector. Objects are stored in some type of list or array called the pool, and handed out to the client on request. This is especially useful when an instance of an object is repeatedly used, or if the object has an expensive initialization aspect to its construction such that it's better to reuse an existing instance than to dispose of an existing one and to create a completely new one from scratch. Let's consider a scenario in which object pooling would be useful. Consider a loop wherein you want to compare the values in the record with a static value.
    The code might contain a loop that does something like this:

    <script type=&quot;syntaxhighlighter&quot; class=&quot;brush: csharp&quot;>
    <![CDATA[
    while (IsRecordAvailable()){
        Employee record = GetNextRecord();
        ... // process record
    }]]>
    </script> 

    In this loop, a new employee Record is returned each time the loop is executed. The most obvious implementation of the GetNextRecord method would create a new object each time it is called, requiring the object to be allocated, initialized, eventually garbage collected, and finalized if the object has a finalizer. When using an object pool, the allocation, initialization, collection, and finalization only occur once, reducing both the memory usage and the processing time that is required.
    In some situations, the code could be rewritten to take advantage of a Clear method on the type with code like this:

    Employee record = new Employee ();
    while (IsRecordAvailable())
    {
        record.Clear();
        FillNextRecord(record);
        ... // process record
    }


  4. Garbage Collection.

    You should almost never call GC.Collect() manually. And by almost I mean once in a lifetime, not once per application, and certainly not once per function call. I occasionally call GC.Collect() for testing purposes just to see if memory has been released. Normally you would never call it. The GC is self-balancing and by calling GC.Collect() you are disrupting that balance.


  5. Managed Heap.

    When you initialize a new process, the runtime .NET environment reserves a contiguous address space for the process. This reserved address space is called the managed heap. The managed heap maintains a pointer to the address where the next object in the heap will be allocated. Initially, this pointer is set to the managed heap's base address. All reference types are allocated on the managed heap. When an application creates the first reference type, memory is allocated for the type at the base address of the managed heap. When the application creates the next object, the garbage collector allocates memory for it in the address space immediately following the first object. As long as address space is available, the garbage collector continues to allocate space for new objects in this manner. Allocating memory from the managed heap is faster than unmanaged memory allocation.


  6. Session handling.

    ASP.NET provides various modes of session state storage. This can be changed by the programmer using the mode attribute of tag in your web application’s Web.config file. Below is a sample of this tag:
    < sessionState mode="InProc"
        stateConnectionString="tcpip=127.0.0.1:42424"
        sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
        cookieless="false" 
        timeout="20" />
    

    AttributeOptionDescription
    mode
    Specifies where to store the session state.

    OffDisables session state management.

    InProcSession state is stored locally in memory of ASP.NET worker process.

    StateServerSession state is stored outside ASP.NET worker process and is managed by Windows service. Location of this service is specified by stateConnectionString attribute.

    SQLServerSession state is stored outside ASP.NET worker process in SQL Server database. Location of this database is represented by sqlConnectionString attribute.


    We access Session data through a property named Session. This Session property is an object of HttpSessionState class in System.Web.SessionState namespace.

Wednesday 25 September 2013

Hiding and Displaying div tag content in real time using Jquery.

Hi Viewers,

This article describes about hiding and displaying the division tags using JQuery with out any postback to the page.
There are many situations you need to hide the div(block of code) in the real time and This can be achieved using JQuery.
This example demonstrate the three scenarios of registering user.
  1. Register Directly.
  2. Register Via Facebook Account.
  3. Register Via Gmail Account.
Download the example from the below link and debug it. This kind of examples are commonly used in any web application and it is very helpful interview question.

Download Link:  Hiding and Displaying div tag Content in real time using Jquery.
Make this Page as Start-up Page: HidingandDisplayingDiv.aspx 

Apart from that it also includes the other example: Real Time ASP.Net Dropdown Binding implementation in web application
ReferenceLink: http://realtimeaspdotnet.blogspot.in/2013/09/real-time-aspnet-dropdown-binding.html



Register Directly


Register With Facebook Account






Register With Gmail Account



Generated Output


In order to get the above result:
  • Create 3 radio buttons by specifying the group name.
  • Create three <div> blocks with unique id.
    • In the above Example there are three <div> with unique Ids
      • <div id="RegisterDiv" style="float: left; width: 100%; display: none; margin-top: 10px;" >
      •    <div id="RegisterFacebookDiv" style="float: left; width: 100%; display: none; margin-top: 10px;">
      •  <div id="RegisterGmailDiv" style="float: left; width: 100%; display: none; margin-top: 10px;">
  • For each radio button specify the onclick="Register('RegisterGmail');"  function and implement the Register method in java script.
  • Place All the controls in <divs> that needs to be rendered on the page.

  •    <script lang="javascript" type="text/javascript">
            function Register(value) {
                if (value == "Register") {
                    $("#RegisterDiv").css('display', 'block');
                    $("#RegisterFacebookDiv").css('display', 'none');
                    $("#RegisterGmailDiv").css('display', 'none');

                }
                else if (value == "RegisterFacebook") {
                    $("#RegisterDiv").css('display', 'none');
                    $("#RegisterFacebookDiv").css('display', 'block');
                    $("#RegisterGmailDiv").css('display', 'none');
                }
                else if (value == "RegisterGmail") {
                    $("#RegisterDiv").css('display', 'none');
                    $("#RegisterFacebookDiv").css('display', 'none');
                    $("#RegisterGmailDiv").css('display', 'block');
                }
            }
        </script>
  • Include Latest Jquery java script file. <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
  • function Register(value) function checks the value and based on the value it hides and displays the <div>
  • These <Divs> can be displayed or can be hide by using   $("#DivisionID").css('display', 'block');
That`s all.

Please share this useful information with other.If you are interested in reading my articles click on Join this site button located below blog archive.

Sunday 22 September 2013

Increasing Performance of ASP.Net web application.

Hi Viewers,

This article describes  techniques to increase the performance of Asp.Net web application.

While developing large application performance is the major factor. Performance plays crucial role in development of any application. There are many ways to increase the performance of the application.Some of them are discussed below.
  1.  Page Level and Server controls:
  2.  State Management Level:
  3.  Data Access Level: 
  4.   Web Application Level:
  • Page Level and Server controls:
    • Avoid unnecessary round trips to the server.
      • use Microsoft Ajax and partial-page rendering to accomplish tasks in browser code.
    • use IsPostBack Property of page object to avoid unnecessary processing.
      • Avoid executing code on each postback if it only has to run the first time the page is requested.
    • while developing custom server controls. design them to render client script for some of their functionality.
      • Creating Custom Client Script by Using the Microsoft Ajax Library.
    • Use Server.Transfer and cross-page posting to redirect between ASP.NET pages in the same application.(For accessing controls and their values from the source page).
    • Leave buffering on unless you have a specific reason to turn it off .  
      • There is a significant performance cost for disabling buffering of ASP.NET Web pages.
  •  State Management:
    •   Use View state of control when it is required.
      • By default, view state is enabled for all server controls. Disable it , by setting  EnableViewState property to false, as in the following example:
        <asp:datagrid enableViewState="false" datasource="..." runat="server"/>
    • Avoid using view state encryption unless you have to.
      • View state encryption prevents users from reading view-state values in the hidden view-state form field.
    • Select appropriate session-state provider for your application
      • Asp.Net provides various ways to store data in a session.Based on the requirement and conditions of the application select appropriate session storage. Example:in-process session state, out-of-process session and creating custom session also possible.
    • Disable session state when you are not using it.
      • To disable session state for a page, set the EnableSessionState attribute in the @ Page directive to false, as in the following example:
        <%@ Page EnableSessionState="false" %>
        To disable it at application level,Use this property in web.config. 
         <sessionState mode="Off" /> 
        
        
  •  Data Access Level:
    • Use SQL Server and stored procedures for data access:
      • SQL Server is the recommended choice for data storage to create high-performance, scalable Web applications.
    • Use the SqlDataReader class for a fast forward-only data cursor:
      • The SqlDataReader class creates a forward-only, read-only data stream that is retrieved from a SQL Server database. 
    • Cache data and page output whenever possible:
      • use caching if there is no dynamic content request for every page request.
    • Use SQL cache dependency appropriately.
      • Use Table-based polling feature provided by SQL Server. In table-based polling, if any data in a table changes, all cache items that are dependent on the table are invalidated
    • Use data source paging and sorting instead of UI:
      • Don`t pull all the data from the database. use paging concepts and retrieve the number of records that are necessary to display.
    • Balance the security benefit of event validation with its performance cost.
    • Use SqlDataSource control caching, sorting, and filtering .
        
  •  Web Application Level:
    • Preload the application.
      • initial start up response time can be improved by preloading.
    • Precompile Web site projects. 
      • Initially project is batch compiled upon first request and this batch compilation compiles all pages in a directory to improve memory and disk usage.So  Precompile the whole project before deploying it into the server.
    • Disable debug mode
      • Disable debug mode before you deploy a production application.
    • Tune the configuration files for the Web server computer and for specific applications.
    • Recycle processes periodically.
    • Set the number of threads per worker process.
    • For applications that rely extensively on external resources, enable Web gardening on multiprocessor computers.    

    Thursday 19 September 2013

    Real Time ASP.Net Dropdown Binding implementation in web application

    Hi viewers,

    This is my 4th post and i think you people will feel very interesting while reading this article and you will improve coding skills after debugging the code.

    Please download the code and debug it. i am sure you will get lot more knowledge on real time web application development. you will find the structure of web application,using of master pages,re-usability of code and  things related to naming conventions,Entity creations,Data accesssing and lot more.

    Download LINK: real time asp.net dropdown binding download

    In the above link you can find the example of how a drop down is binded in real time web application development with the entities. In this example i will use only one method for binding thousands of drop downs across the application.Don`t get shocked,this is possible and i love this quote "Write once and use it many times". In the example only one drop down is binded but you can bind "n" number of drop downs by calling only one method. 

    Look at the method in the downloaded example:

                     ToggleControlOnlyBlank(ByRef workingddl As DropDownList, ByRef workinglist As Object,  ByVal intItemCount As Int16,  ByVal ddlvalue As String, ByVal ddlText As String,  ByVal enabled As Boolean, ByVal addBlankText As Boolean, ByVal autoPostBack As Boolean, ByVal Visible As Boolean, _Optional ByVal defaultValue As Integer = Nothing)




    i am making this method as shared method and placing it in a common utility class. So that it is accessible across the application and not necessary to create an object to call this method every time. In the same way you can re-use the code for different purposes.

    Why Common utility class?
                        Because it is very meaningful when we place all the methods which are frequently used in the application.

    i hope you will enjoy this while debugging the code.

    Please comment it if you have any queries. I will respond to your queries in my free time.

    Tuesday 17 September 2013

    Different ways to achieve code re-usability in real time Asp.Net



    Most of the people know inheritance is the major way for re-usability of code. Apart from that their are other ways of code re-usability. This article is very useful for the people who are preparing for interviews as well as the employees who are working in software industry.

    This article describes  how people re-use the code in software Industry. This article is little big so don`t get hesitate to read this article. You will find very helpful information with an example.
    1. Using Master Pages. (Example .Master Pages in asp.net).
    2. Using User Controls. (Example: .ascx  Custom Controls ).
    3. Using Singleton Classes. (To prevent identical objects from being created)
    4. Using Entities. (Re-usability of Entities are very important in real time implementations).
    5. Inheritance and Shared Methods. (is-a Relationship and Has-a Relationship)
    6. Creating COM Components. (.dll class libraries interoperability between languages)

      Master Pages
      :
      • To create a set of controls that are common across all the web pages and attaching them to all the web pages.
      • A centralized way to change the above created set of controls which will effectively change all the web pages.
      • Changing the UI elements dynamically on master page from content pages based on user choice.
      • Nested Master Pages are also Possible. 

      Using of Master Pages: 
      • Whenever you create "Master pages" use content place holders inside master page where you can specify the controls to be rendered.
      • Use Same Content place holders id in the derived page and create your customized content in that content place holder.

      Normally in software industry Master Pages are placed in the below path
      Path= ~/Assets/masterpages/MasterPage.master

      In Any Real time development Must and should you master pages and it is recommended.
      MasterPagesMerge graphic


      User Controls: In addition to using Web server controls in your ASP.NET Web pages, you can create your own custom, reusable controls using the same techniques you use for creating ASP.NET Web pages. These controls are called user controls.
      • User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it.
      •  Custom controls. A custom control is a class that you write that derives from control or web control.
        A user controls differs from an ASP.NET Web page in these ways:
        • The file name extension for the user control is .ascx.
        • Instead of an @page directive, the user control contains an @control directive that defines configuration and other properties.
        • User controls cannot run as stand-alone files. Instead, you must add them to ASP.NET pages, as you would any control.
        • The user control does not have html, body, or form elements in it. These elements must be in the hosting page.
       Use this tag in a page for registering the user control in a page:
      <%@ Register TagPrefix="Grid" TagName="RequestData" Src="~/Users/Controls/ConnectionControl.ascx" %> 
      Use this tag as many times you want to use this control in your page
       <Grid:RequestData ID="rgInbox" runat="server" />
       
      How to Access Page Methods from user controls and Vice Verse?
                   Page methods can be accessed from user control using Reflection and finding the control or value in user control can be accessed in page by using  Me.Parent.FindControl("controlname").                          
                                                             
      Singleton Classes: To Make sure to create only one instance and  there is a global access point to that object then singleton classes play an important role. This is one design pattern. Now i am just giving an idea how to create singleton class. Example:Garbage Collection.
      singleton Class
      Imports System
      Public Class Singleton
          Private Shared instance As Singleton
           Private Sub New()
             MyBase.New
           End Sub
      
           Public Shared ReadOnly Property GetInstance As Singleton
             Get
                  If(instance Is Nothing) Then
                      instance = New Singleton
                  End If
                  Return instance
              End Get
           End Property
      
      End Class
      How to create an instance?
      Singleton.GetInstance()-----Use ClassName.MethodName

      Using Entities : Like Methods and Classes class entities can be reused.

      User.vb: This class consists of user properties with setter() and getter() methods.
      • user class properties: UserName,FirstName,LastName,Address,Mobile,DateOfBirth.

      Account.vb: This class consists of Account properties with setter() and getter() methods.
      • Account class properties: AccountId, AccountName, AccountType, AccountCreated, AccountUpdated.

      How to Re-use Entities?
      • Here to re-use User class entities in Account class as mentioned below
        public property AccountDetails as User
        For accessing in application you can use:  AccountDetails.UserName or AccountDetails.FirstName.

      Inheritance and Shared Methods:
      Inheritance is a process of inheriting properties and methods from parent class to child class. If an object is created to the child class then parent class constructor will be called first and  child class method will be executes.

      1. Single Inheritance
      2. Hierarchical Inheritance
      3. Multi Level Inheritance
      4. Hybrid Inheritance
      5. Multiple Inheritance

      All the types of inheritance can be achieved in Object Oriented Programming except Multiple Inheritance. Multiple inheritance can be implemented using Interfaces.

      Major People feel difficulty to explain the below question in interview
      Why Multiple inheritance is not possible?
                   
                    Reason 1: Problem around Diamond problem, consider a class A has run() method and then B and C derived from A and has there own run() implementation and now class D derive from B and C using multiple inheritance and if we refer just run() compiler will not be able to decide which run() it should invoke. This is also called Diamond problem because structure on this inheritance scenario is similar to 4 edge diamond, see below
                A run()
              /      \
            /          \
         B run()     C run()
            \          /
              \     /
               D run()
                 Even if we remove the top head of diamond class A and allow multiple inheritances we will see this problem of ambiguity.

                  Reason 2: Multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity. Also .net avoids this ambiguity by supporting single inheritance with interfaces. Since interface only have method declaration and doesn’t provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.

      Shared Methods : Shared methods are majorly used in any application they re-use these methods many types in the application like making all the string safer while retrieving it from database and using common methods to bind controls like dropdown control.

      Example: Creating shared method for binding the drop down and re-use it whenever necessary to bind the different drop downs in the application. Concept of  "Write Once and use Many times."

      COM Components: Component Object Model is a method to facilitate communication between different applications and languages. The interesting thing in COM components and  widely accepted interoperability standard and explains the way the memory should be organized for all the objects.

      Creating COM Components
      • Create a new Class Library project.
      • Create a new interface, say IManagedInterface, and declare the methods required. Then provide the Guid (this is the IID) for the interface using the GuidAttribute defined in System.Runtime.InteropServices. The Guid can be created using the Guidgen.exe. [Guid("3B515E51-0860-48ae-B49C-05DF356CDF4B")]
      • Define a class that implements this interface. Again provide the Guid (this is the CLSID) for this class also.
      • Mark the assembly as ComVisible. For this go to AssemblyInfo.cs file and add the following statement [assembly: ComVisible (true)]. This gives the accessibility of all types within the assembly to COM.
      • Build the project. This will generate an assembly in the output path. Now register the assembly using regasm.exe (a tool provided with the .NET Framework)- regasm \bin\debug\ComInDotNet.dll \tlb:ComInDotNet.tlb This will create a TLB file after registration.
      • Alternatively this can be done in the Project properties -> Build -> check the Register for COM interop.
      Please share this helpful information with your friends.

      My next post will be on real time dropdown binding with an example and re-using the code to bind thousands of   dropdowns in web application.

    Saturday 14 September 2013

    The Structure of an Asp.Net real time web application

    Hi Viewers

    This page describes the structure of a real time web application and the steps to be followed for creating such structure.

    A real time web application has a layered structure as described below
    1. Data Access Object Layer (DAO) : To interact with data base and get the data tables and put it into a list with the help of entity objects.
      Example:  list(of MySampleApplication.Sample.Entities.User.User)
      This list is returned to the implementation layer and the implementation layers handovers the list to the asp.net application layer and there we bind it to grid or drop downs or to other data controls.
    2. Entities Layer: Consists of Entity class properties.These properties can only be accessed through set and get method as Properties are declared with Private keyword.
    3. Interface Layer:  Consists of all user defined interfaces which are implemented in implementation layer.
    4. Implementation Layer: Consists of Implementation of interfaces and creation of an object of DAO to call the methods in DAO class.
    5. Utilities: Consists of the shared classes and the methods that are most frequently called in application.
      Example:Making string safer,checking for  nulls,connection methods and other common methods


    Description for the above structure and the used design pattern will be posted later . Please have a look at below Real time structure and its implementation.


    You can download the sample application from the below link:

    Link : https://drive.google.com/folderview?id=0BxHH0xtw0daaclZNdHFtb3g1Ync&usp=sharing

    My next post will be on "Code Re-usability in asp.net."

    Please share this helpful information with your friends.


    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"];