Monday 16 June 2014

ASP.NET Page Output Cache

ASP.NET Caching is used to build high-performance, scalable ASP.NET web applications by storing responses in memory. On subsequent requests, the page code is not executed and the cached output is used to serve the request. 

By default, when we request an ASP.NET website, every request is processed by many stages, such as Page initialization, Load, Rendering, etc. This consumes a lot of resources on the server. Consider the following scenario: many customers browse ASP.NET websites for a news page and the news page won’t change for several hours. Based on a common route, when multiple customers request the same news page at almost the same time, ASP.NET will execute the same code to generate the response with the same news multiple times. This is a resource wasting process. Hence, we start thinking whether we can generate the response once and serve multiple customers with it. The answer is Cache.

Output Cache has the advantage of being simple to implement, and is sufficient in most cases. It simply keeps a copy of the response that was sent to the client in memory and subsequent requests are then responded with the cached output until the cache expires, which incredibly improves the ASP.NET web application performance.

For ASP.NET Output Cache, ASP.NET uses @ OutputCache to declare many attributes to control the output caching policies of the ASP.NET page or a user control contained in a page.

  • Drag and drop a DropDownList in the page and add three items to it.
  • Add @OutputCache in the ASPX markup and specify the expiration time and VaryByControl attribute. For example: OutputCache Duration="100" VaryByControl="ddlitemselection".
  • Run the ASP.NET web application and launch this page, we can see that the different items have their corresponding cache.

Sample Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JScript.aspx.cs" Inherits="Javascript.JScript" %>
<%@ OutputCache Duration="100" VaryByParam="ddlitemselection" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function Test() {
        alert("hi");
        $("#trOpen").show();
    }
    function AnotherFunction() {
        alert("This is another function");
    }
    $(document).ready(function () {
        $(".TestStyle").click(function () {
            alert("Welcome");
        });
    });

</script>
    <style>
        .TestStyle {
            font: 12pt verdana;
            font-weight: 700;
            color: orange;
        }

         .TestStyle1 {
            font: 12pt verdana;
            font-weight: 800;
            color: red;
        }
    </style>
</head>

<body>
<form id="form2" runat="server">
<table>
    <tr><td>
            <asp:RadioButtonList ID="rbtntest" runat="server" onchange="Test()">
               <asp:ListItem>ram</asp:ListItem>
               <asp:ListItem>Sri</asp:ListItem>
               <asp:ListItem>Sriram</asp:ListItem>
            </asp:RadioButtonList>
        </td>
    </tr>
    <tr id="trOpen"style="display:none">
         <td>
            <asp:Button ID="MyButton" runat="server" Text="Ok" OnClick="MyButton_Click" />

           
        </td>
    </tr>
    <tr><td>
         <asp:Button ID="Button1" runat="server" CssClass="TestStyle" Text="Click me" />
             <asp:Button ID="Button2" runat="server" CssClass="TestStyle" Text="Touch me" />
        </td></tr>
    <tr><td>
        <asp:DropDownList ID="ddlitemselection" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlitemselection_SelectedIndexChanged"></asp:DropDownList></td></tr>
    <tr><td>

        <asp:GridView ID="grd" runat="server"></asp:GridView>
        </td></tr>
    </table>
</form>
</body>
</html>


CS code:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Javascript
{
    public partial class JScript : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable t = new DataTable();
                string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
                using (SqlConnection con = new SqlConnection(conn))
                {
                    con.Open();
                    using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM SampleTable", con))
                        a.Fill(t);
                }
                grd.DataSource = t;
                grd.DataBind();
                ddlitemselection.Items.Add("Madurai");
                ddlitemselection.Items.Add("Sivakasi");
                ddlitemselection.Items.Add("Sirukkulam");
                ddlitemselection.Items.Add("Channai");
                ddlitemselection.Items.Add("Nellai");
                ddlitemselection.DataBind();
            }
        }

        protected void MyButton_Click(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true);
        }

        protected void ddlitemselection_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataTable t = new DataTable();
            string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
            using (SqlConnection con = new SqlConnection(conn))
            {
                con.Open();
                using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM [SampleDB].[dbo].[SampleTable] where Address='" + ddlitemselection.SelectedItem.Text+"'", con))
                    a.Fill(t);
            }
            grd.DataSource = t;
            grd.DataBind();
        }
    }
}