dotnet - Caching

Embed Size (px)

DESCRIPTION

DOTNET CACHING

Text of dotnet - Caching

  • 0

    Rakesh Singh NARESH I TECHNOLOGIES Hyderabad

    ASP.NET - Caching

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 1

    ASP.NET Caching Overview:

    One of the most important factors in building high-performance, scalable Web applications is the ability to store items,

    whether data objects, pages, or parts of a page, in memory the initial time they are requested. You can cache, or store,

    these items on the Web server or other software in the request stream, such as the proxy server or browser. This allows

    you to avoid recreating information that satisfied a previous request, particularly information that demands significant

    processor time or other resources. ASP.NET caching allows you to use a number of techniques to store page output or

    application data across HTTP requests and reuse it.

    Caching is a technique of persisting the data in memory for immediate access to requesting program calls.

    We can say Caching is a technique of storing frequently used data/information in memory, so that, when the same

    data/information is needed next time, it could be directly retrieved from the memory instead of being generated by the

    application.

    Caching is extremely important for performance boosting in ASP.Net, as the pages and controls are dynamically generated

    here. It is especially important for data related transactions, as these are expensive in terms of response time.

    Caching is perfect tool to enhance performance. Basically Caching enables you to store the expensive data into Cache

    object and later retrieve it without doing expensive operations.

    An application can often increase performance by storing data in memory that is accessed frequently and that requires

    significant processing time to create. For example, if your application processes large amounts of data using complex logic

    and then returns the data as a report accessed frequently by users, it is efficient to avoid re-creating the report every time

    that a user requests it. Similarly, if your application includes a page that processes complex data but that is updated only

    infrequently, it is inefficient for the server to re-create that page on every request.

    To help you increase application performance in these situations, ASP.NET provides caching using two basic caching

    mechanisms. The first is application caching, which allows you to cache data you generate, such as a DataSet object or a

    custom report business object. The second is page output caching, which saves the output of page processing and reuses

    the output instead of re-processing the page when a user requests the page again.

    Why Caching?

    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 wont 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.

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 2

    Advantages of Caching:

    1. Reduce hosting server round-trips

    When content is cached at the client or in proxies, it cause minimum request to server.

    2. Reduce database server round-trips

    When content is cached at the web server, it can eliminate the database request.

    3. Reduce network traffic

    When content is cached at the client side, it also reduce the network traffic.

    4. Avoid time-consumption for regenerating reusable content

    When reusable content is cached, it avoid the time consumption for regenerating reusable content.

    5. Improve performance

    Since cached content reduce round-trips, network traffic and avoid time consumption for regenerating

    reusable content which cause a boost in the performance.

    Types of Caching:

    The ASP.NET Web Application Framework supports the following types of caching:

    Page Output Caching

    Fragment Caching (Partial Page Caching)

    Data Caching

    1. Page Output Caching

    A typical kind of caching for server applications is output caching. Output caching enables you to store rendered HTML.

    The stored HTML is served in response to subsequent requests for the same page. You can use output caching to cache a

    whole Web page or just the output of an ASP.NET web user control.

    The page output cache stores the contents of a processed ASP.NET page in memory. This lets ASP.NET send a page

    response to a client without going through the page processing life cycle again. Page output caching is especially useful for

    pages that do not change often but that require significant processing to create. For example, if you are creating a high-

    traffic Web page to display data that is not frequently updated, page output caching can dramatically increase the

    performance of that page. Page caching can be configured individually for each page, or you can create cache profiles in

    the Web.config file, which allow you to define caching settings once and then use those settings with multiple pages.

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 3

    Page output caching provides two models for page caching: Full-Page Caching (Page Level Caching) and Partial-Page

    Caching (Fragment Caching). Full-page caching persists the complete contents of a page and uses the cached page content

    to fulfil client requests. Partial-page caching persists specified portions of a page and lets other portions of the page be

    created dynamically.

    The page level output caching can be done using @OutputCache directive. It stores complete response of page output into

    the memory (Server Memory)

    @ OutputCache Directive:

    Attributes:

    Duration - It is used to define the time in seconds to cache the page response in memory.

    VaryByParam: It is used to set the value to get Single Response or Multiple Response.

    Ex:

    The Duration parameter specifies how long, in seconds, the HTML output of the Web page should be held in the cache. When the duration expires, the cache becomes invalid and, with the next visit, the cached content is flushed, the ASP.NET

    Web page's HTML dynamically generated, and the cache repopulated with this HTML.

    The VaryByParam parameter is used to indicate whether any GET (QueryString) or POST (via a form submit with method="POST") parameters should be used in varying what gets cached. In other words, multiple versions of a page can be cached if the output used to generate the page is different for different values passed in via either a GET or

    POST.

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 4

    Example1:

    Create an aspx page to show the server date time as well as client date time but store server-side date time response in

    memory using OutputCache with a specified duration in seconds. So when we make a request to access that particular page first time it goes through entire application process & cached in memory, then send to client machine but when we

    make next time request it doesnt go through the entire application process as it was already stored in memory. So it just gives output from the memory itself but if the specified time duration expired then again start through the entire application

    process.

    Design View:

    Source View:

    RakeshDotNet-Caching Example

    Server - Side Date Time:

    Client - Side Date Time:

    document.write(Date());

    Code View:

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    public partial class CachingEx1 : System.Web.UI.Page

    {

    protected void Page_Load(object sender, EventArgs e)

    {

    System.Threading.Thread.Sleep(5000);

    Label1.Text = DateTime.Now.ToString();

    }

    }

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 5

    Example2: Working with VaryByParam Attributes to get multiple responses from the memory via control request.

    Design View:

    Source View:

    RakeshDotNet-Caching Example

    Select Dept:

    Client - Side DateTime:

    document.write(Date());

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 6

    Code View:

    using System;

    using System.Collections.Generic; using System.Linq;

    using System.Web; using System.Web.UI;

    using System.Web.UI.WebControls;

    using System.Data;

    using System.Data.SqlClient;

    public partial class CachingEx2 : System.Web.UI.Page

    { SqlConnection cn = null;

    SqlDataAdapter da = null; DataSet ds = null;

    string strSqlQuery = String.Empty;

    protected void Page_Load(object sender, EventArgs e) {

    cn = new SqlConnection("Data Source=(local);Database=DemoDB;User Id=sa;Password=123");

    if (!Page.IsPostBack)

    { BindDeptDDL();

    BindEmpData(ddlDept.SelectedItem.Value);

    } }

    void BindDeptDDL()

    { strSqlQuery = "Select * from Dept";

    da = new SqlDataAdapter(strSqlQuery, cn); ds = new DataSet();

    da.Fill(ds, "Dept");

    ddlDept.DataSource = ds.Tables["Dept"]; ddlDept.DataTextField = "DeptName";

    ddlDept.DataValueField = "DeptId"; ddlDept.DataBind();

    ddlDept.Items.Insert(0, new ListItem("All", "0"));

    }

    void BindEmpData(string deptId) {

    if (deptId == "0") {

    strSqlQuery = "Select * from Emp";

    } else

    { strSqlQuery = "Select * from Emp Where DeptId=" + deptId;

    }

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 7

    da = new SqlDataAdapter(strSqlQuery, cn);

    ds = new DataSet();

    da.Fill(ds, "Emp");

    GridView1.DataSource = ds.Tables["Emp"]; GridView1.DataBind();

    Label1.Text = "Data Fetched At: " + DateTime.Now.ToString(); }

    protected void ddlDept_SelectedIndexChanged(object sender, EventArgs e)

    {

    BindEmpData(ddlDept.SelectedItem.Value); }

    }

    Example3: Working with VaryByParam Attributes to get multiple responses from the memory via QueryString request.

    DesignView:

    Source View:

    RakeshDotNet-Caching Example

    Click Any of Following Below Dept:

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 8

    Client - Side Date & Time:

    document.write(Date());

    Code View: using System;

    using System.Collections.Generic; using System.Linq;

    using System.Web;

    using System.Web.UI; using System.Web.UI.WebControls;

    using System.Data;

    using System.Data.SqlClient;

    public partial class CachingEx3 : System.Web.UI.Page

    { SqlConnection cn = null;

    SqlDataAdapter da = null; DataSet ds = null;

    string strSqlQuery = String.Empty;

    protected void Page_Load(object sender, EventArgs e) {

    cn = new SqlConnection("Data Source=(local);Database=DemoDB;User Id=sa;Password=123");

    if (!Page.IsPostBack)

    { BindDeptBulletedList();

    if (Request.QueryString["DeptId"] != null) {

    BindEmpByDept(); }

    } }

    void BindDeptBulletedList() {

    strSqlQuery = "Select * from Dept"; da = new SqlDataAdapter(strSqlQuery, cn);

    ds = new DataSet();

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 9

    da.Fill(ds, "Dept");

    DataRowCollection drc = ds.Tables["Dept"].Rows;

    foreach (DataRow dr in drc) {

    BulletedList1.Items.Add(new ListItem(dr["DeptName"].ToString(),"~/CachingEx3.aspx?DeptId=" + dr["DeptId"].ToString()));

    }

    }

    void BindEmpByDept() {

    System.Threading.Thread.Sleep(5000);

    string deptId = Request.QueryString["DeptId"].ToString();

    strSqlQuery = "Select * from Emp Where DeptId=" + deptId; da = new SqlDataAdapter(strSqlQuery, cn);

    ds = new DataSet(); da.Fill(ds, "Emp");

    GridView1.DataSource = ds.Tables["Emp"];

    GridView1.DataBind();

    Label1.Text = "Data Fetched At: " + DateTime.Now.ToString(); }

    }

    2. Fragment Caching

    Partial-Page Output Caching, or page fragment caching, allows specific regions of pages to be cached. ASP.NET provides

    a way to take advantage of this powerful technique, requiring that the part(s) of the page you wish to have cached appear

    in a User Control. One way to specify that the contents of a User Control should be cached is to supply

    an OutputCache directive at the top of the User Control. That's it! The content inside the User Control will now be cached

    for the specified period, while the ASP.NET Web page that contains the User Control will continue to serve dynamic content.

    (Note that for this you should not place an OutputCache directive in the ASP.NET Web page that contains the User Control

    - just inside of the User Control.)

    Fragment caching refers to the caching of individual user controls within a Web Form. Each user control can have

    independent cache durations and implementations of how the caching behaviour is to be applied. Fragment caching is

    useful when you need to cache only a subset of a page.

    Fragment caching allows to cache specific portions of the page rather than the whole page. It is done by implementing

    the page in different parts by creating everything in form of user controls and caching each user control individually.

    Example1: We use fragment caching in a situation where we dont want to store response of whole page in memory,

    instead of this we may want to store some portion of a page in memory. So to do this we may take the help of Web User

    Control and OutputCache Directive in web user control only, not in an aspx page.

    Create a Web User Control (ucCaching.ascx) that display the server date time and store into the memory for the next 30

    seconds using OutputCache Directive as following:

    Design View:

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 10

    Server Date & Time From User Control:

    Code View:

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    public partial class ucCaching : System.Web.UI.UserControl

    {

    protected void Page_Load(object sender, EventArgs e)

    {

    lblDateTime.Text = DateTime.Now.ToString();

    }

    }

    Create the Web Form to Contain the User Controls:

    You can now create the Web Form (.aspx) to contain the newly developed user control.

    Create an ASP.NET Page (CachingEx4.aspx) to use this Web User Control (ucCaching.ascx) as well as on this page also display the server date time but when we run page, page based server date time will keep changing on every request whereas web user control based server date time wont change till the next 30 seconds as it is already cached in memory, so it keep giving response from memory itself rather than generating through the entire application process.

    CachingEx4.aspx: Design View:

    Source View:

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 11

    Server Date & Time From Page:

    Code View: using System;

    using System.Collections.Generic;

    using System.Linq; using System.Web;

    using System.Web.UI; using System.Web.UI.WebControls;

    public partial class CachingEx4 : System.Web.UI.Page {

    protected void Page_Load(object sender, EventArgs e) {

    lblDateTime.Text = DateTime.Now.ToString(); }

    }

    3. Data Caching

    In simple terms data caching is storing data in memory for quick access. Typically information that is costly to

    obtain (in terms of performance) is stored in the cache. One of the more common items stored in a cache in a

    Web application environment is commonly displayed database values; by caching such information, rather than

    relying on repeated database calls, the demand on the Web server and database server's system resources are

    decreased and the Web application's scalability increased. As Microsoft articulately puts it, "Caching is a

    technique widely used in computing to increase performance by keeping frequently accessed or expensive data

    in memory. In the context of a Web application, caching is used to retain pages or data across HTTP requests

    and reuse them without the expense of recreating them."

    OR

    Data caching means caching data from a data source. As long as the cache is not expired, a request for the

    data will be fulfilled from the cache. When the cache is expired, fresh data is obtained by the data source and

    the cache is refilled.

    Caching enables you to store data in memory for rapid access. Applications can access the cache and not have

    to retrieve the data from the original source whenever the data is accessed. This avoids repeated queries for

    data, and it can improve performance and scalability.

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 12

    OR

    Data Cache is used to storing frequently used data in the Cache memory. It's much efficient to retrieve data from the data

    cache instead of database or other sources. We need use System.Web.Caching namespace. The scope of the data caching

    is within the application domain unlike "Session". Every user can able to access this objects.

    How Data Caching Works?

    When client request to the server, server execute the stored procedure or function or select statements on the

    Sql Server Database then it returns the response to the browser. If we run again, same process will happen on

    the web server with Sql Server.

    In the very first time retrieve the records from the Sql Server Database and stored into the Cache memory. After

    that records will retrieve from Cache memory (IIS). We can set expiration period time after expiration time over

    the caching again it will hit the Sql Server database and stored into the cache memory and next retrieve will

    happen on the data cache memory.

    Example1:

    Source View:

    RakeshDotNet Caching Example

    Code View:

    using System; using System.Collections.Generic;

    using System.Linq; using System.Web;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    using System.Web.Caching;

    public partial class CachingEx5 : System.Web.UI.Page

    { protected void Page_Load(object sender, EventArgs e)

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 13

    {

    if (Page.IsPostBack)

    { lblInfo.Text += "Page Created With Post Back.";

    } else

    {

    lblInfo.Text += "Page Created Without PostBack."; }

    if (Cache["TestItem"] == null)

    {

    lblInfo.Text += "Creating Test Item."; DateTime testItem = DateTime.Now;

    lblInfo.Text += "Storing test item in cache for 60 seconds."; Cache.Insert("TestItem", testItem,null,

    DateTime.Now.AddSeconds(60), TimeSpan.Zero); }

    else

    { lblInfo.Text += "Retrieving Test Item.";

    DateTime testItem = (DateTime)Cache["TestItem"];

    lblInfo.Text += "Displaying Stored Date & Time From Cache: " + testItem.ToString();

    } lblInfo.Text += "";

    } }

    Example2:

    Design View (CachingEx6.aspx):

    RakeshDotNet Caching Example

  • Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.

    P a g e | 14

    Code View: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Web.Caching; public partial class Default9 : System.Web.UI.Page { SqlConnection cn = null; SqlDataAdapter da = null; DataSet ds = null; protected void Page_Load(object sender, EventArgs e) { cn = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString); if (Cache["EmpData"] == null) { da = new SqlDataAdapter("Select * from Emp", cn); ds = new DataSet(); da.Fill(ds, "Emp"); Cache.Insert("EmpData", ds, null, DateTime.Now.AddSeconds(30), TimeSpan.Zero); lblDateTime.Text = "Data Fetched At: " + DateTime.Now.ToString(); GridView1.DataSource = ds.Tables["Emp"]; GridView1.DataBind(); } else { DataSet dsEmp = (DataSet)Cache["EmpData"]; GridView1.DataSource = dsEmp.Tables["Emp"]; GridView1.DataBind(); } } }

    Conclusion:

    Caching is a technique that definitely improves the performance of web applications if one is careful to have a balance in

    terms of which data needs to be cached and parameter values for expiration policy.