SlideShare a Scribd company logo
1 of 6
What is Caching?
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 places frequently used data in quickly accessed media like the random access memory of the computer.
The ASP.Net runtime includes a key-value map of CLR objects called cache. This lives with the application and is
available via the HttpContext and System.Web.UI.Page.
In some respect, caching is similar to storing the state objects. However, the storing information in state objects is
deterministic, i.e., you can count on the data being stored there, and caching of data is nondeterministic.
The data will not be available if its lifetime expires, or the application releases its memory, or caching does not
take place for some reason.
You can access items in the cache using an indexer and may control the lifetime of objects in the cache and set
up links between the cached objects and their physical sources.
Caching in ASP.Net:
ASP.Net provides the following different types of caching:
 Output Caching: Output cache stores a copy of the finally rendered HTML pages or part of pages sent to the
client. When the next client requests for this page, instead of regenerating the page, a cached copy of the page is
sent, thus saving time.
 Data Caching: 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.
 Object Caching: Object caching is caching the objects on a page, such as data-bound controls. The cached
data is stored in server memory.
 Class Caching: Web pages or web services are compiled into a page class in the assembly, when run for the
first time. Then the assembly is cached in the server. Next time when a request is made for the page or service,
the cached assembly is referred to. When the source code is changed, the CLR recompiles the assembly.
 Configuration Caching: Application wide configuration information is stored in a configuration file. Configuration
caching stores the configuration information in the server memory.
Output Caching:
Rendering a page may involve some complex processes like, database access, rendering complex controls etc.
Output caching allows bypassing the round trips to server by caching data in memory. Even the whole page
could be cached.
The OutputCache directive is responsible of output caching. It enables output caching and provides certain
control over its behaviour.
Syntax for OutputCache directive:
<%@ OutputCache Duration="15" VaryByParam="None" %>
Put this directive under the page directive . This tells the environment to cache the page for 15 seconds. The
following event handler for page load would help in testing that the page was really cached.
protected void Page_Load(object sender, EventArgs e)
{
Thread.Sleep(10000);
Response.Write("This page was generated and cache at:" +
DateTime.Now.ToString());
}
The Thread.Sleep() method stops the process thread for the specified time. In this example, the thread is
stopped for 10 seconds, so when the page is loaded for first time, it will take 10 seconds. But next time you
refresh the page, it does not take any time, as the page will retrieved from the cache without being loaded.
The OutputCache directive has the following attributes, which helps in controlling the behaviour of the output
cache:
Attribute Values Description
DiskCacheable true/false
Specifies that output could be written to a
disk based cache.
NoStore true/false
Specifies that the "no store" cache control
header is sent or not.
CacheProfile String name
Name of a cache profile as to be stored in
web.config.
VaryByParam
None
*
Param- name
Semicolon delimited list of string specifies
query string values in a GET request or
variable in a POST request.
VaryByHeader
*
Header names
Semicolon delimited list of strings specifying
headers that might be submitted by a client.
VaryByCustom
Browser
Custom string
Tells ASP.Net to vary the output cache by
browser name and version or by a custom
string.
Location
Any
Client
Downstream
Server
None
Any: page may be cached anywhere.
Client: cached content remains at browser.
Downstream: cached content stored in
downstream and server both.
Server: cached content saved only on
server.
None: disables caching.
Duration Number
Number of seconds the page or control is
cached.
Let us add a text box and a button to the previous example and add this event handler for the button.
protected void btnmagic_Click(object sender, EventArgs e)
{
Response.Write("<br><br>");
Response.Write("<h2> Hello, " + this.txtname.Text + "</h2>");
}
And change the OutputCache directive :
<%@ OutputCache Duration="60" VaryByParam="txtname" %>
When the program is executed, ASP.Net caches the page on the basis of the name in the text box.
OutputCache - varybycontrol
The varybycontrol does exactly what it says - it varies the cache depending on the value of the
specified control. For instance, you can have a dropdownlist with a set of selections, and base the
content of the page based on the selected item. In that case, it will make sense to vary by the value of
this control, since the content of the page changes according to it. Here is an example of using the
varybycontrol parameter:
<%@ OutputCache duration="10" varybyparam="none" varybycontrol="NameOfControl" %>
OutputCache - varybycustom
This is probably the least easy way of using the OutputCache system, but on the other hand, probably
the most flexible. It allows you to handle the variations your self, by setting a custom string, which
ASP.NET will vary the output by. To test this, you need to add a global.asax file to your project, if you
don't already have one. Right click on your project in the Solution Explorer, and select Add new item.
Now select the "Global Application Class" and click Ok. In the Global.asax file, you need to override
the GetVaryByCustomString like this:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
if(custom == "Browser")
{
return context.Request.Browser.Browser;
}
return String.Empty;
}
In this case, our caching will be varied based on which browser the user accesses the page with. The
markup part should be written like this:
<%@ OutputCache duration="120" varybyparam="None" varybycustom="Browser" %>
Try accessing the page from different browsers. You will see that the output now depends on which
browser you use. The Browser object comes with a bunch of useful information about the client
browser - for instance you could vary by whether or not the browser supports CSS, JavaScript or
something else.
OutputCache - varybyheader
This one allows you to vary the content based on one or more of the headers that browser send. Here
is an example:
<%@ OutputCache duration="120" varybyparam="None" varybyheader="Accept-Language"
%>
This will vary cache based on the Accept-Language header, which tells the server which languages
the user accepts and prefers.
Data Caching:
The main aspect of data caching is caching the data source controls. We have already discussed that the data
source controls represent data in a data source, like a database or an XML file. These controls derive from the
abstract class DataSourceControl and have the following inherited properties for implementing caching:
 CacheDuration - sets the number of seconds for which the data source will cache data
 CacheExpirationPolicy - defines the cache behaviour when the data in cache has expired
 CacheKeyDependency - identifies a key for the controls that auto-expires the content of its cache when
removed
 EnableCaching - specifies whether or not to cache data
Example:
To demonstrate data caching, create a new website and add a new web form in it. Add to it a SqlDataSource
control with the database connection already used in the data access tutorials.
For this example, add a label to the page, which would show the response time for the page.
<asp:Label ID="lbltime" runat="server"></asp:Label>
Apart from the label, the content page is same as in the data access tutorial. Add an event handler for the page
load event:
protected void Page_Load(object sender, EventArgs e)
{
lbltime.Text = String.Format("Page posted at: {0}",
DateTime.Now.ToLongTimeString());
}
The design page should look like the following:
When you run the page for the first time, nothing different happens, the label shows that, each time you refresh
the page, the page is reloaded and the time shown on the label changes.
Next, set the EnableCaching attribute of the data source control to be 'true' and set the Cacheduration attribute to
'60'. It will implement caching and the cache will expire every 60 seconds.
Now the timestamp will change with every refresh, but if you change the data in the table within these 60
seconds, it won't show before the cache expires:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:
ASPDotNetStepByStepConnectionString %>"
ProviderName="<%$ ConnectionStrings:
ASPDotNetStepByStepConnectionString.ProviderName %>"
SelectCommand="SELECT * FROM [DotNetReferences]"
EnableCaching="true" CacheDuration = "60">
</asp:SqlDataSource>
Object Caching:
Object caching provides more flexibility than other cache techniques. You can use object caching to place any
object in the cache. The object can be of any type - a data type, a web control, a class, a DataSet object, etc. The
item is added to the cache simply by assigning a new key name. Like:
Cache["key"] = item;
ASP.Net also provides the Insert() method for inserting an object to the cache. This method has four overloaded
versions. Let us see the various versions first.
Overload Description
Cache.Insert((key, value);
Inserts an item into
the cache with the
key name and
value with default
priority and
expiration.
Cache.Insert(key, value, dependencies);
Inserts an item into
the cache with key,
value, default
priority, expiration
and a
CacheDependency
name that links to
other files or items
so that when these
change the cache
item remains no
longer valid.
Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration);
This indicates an
expiration policy
along with the
above issues.
Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration,
priority, onRemoveCallback);
This along with the
parameters also
allows you to set a
priority for the
cache item and a
delegate that,
points to a method
to be invoked
when the item is
removed.
Sliding expiration is used to remove an item from the cache when it is not used for the specified time span. The
following code snippet stores an item with a sliding expiration of 10 minutes with no dependencies.
Cache.Insert("my_item", obj, null, DateTime.MaxValue,
TimeSpan.FromMinutes(10));
Example:
Create a page with just a button and a label. Write the following code in the page load event:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
lblinfo.Text += "Page Posted Back.<br/>";
}
else
{
lblinfo.Text += "page Created.<br/>";
}
if (Cache["testitem"] == null)
{
lblinfo.Text += "Creating test item.<br/>";
DateTime testItem = DateTime.Now;
lblinfo.Text += "Storing test item in cache ";
lblinfo.Text += "for 30 seconds.<br/>";
Cache.Insert("testitem", testItem, null,
DateTime.Now.AddSeconds(30), TimeSpan.Zero);
}
else
{
lblinfo.Text += "Retrieving test item.<br/>";
DateTime testItem = (DateTime)Cache["testitem"];
lblinfo.Text += "Test item is: " + testItem.ToString();
lblinfo.Text += "<br/>";
}
lblinfo.Text += "<br/>";
}
When the page is loaded for the first time it says:
Page Created.
Creating test item.
Storing test item in cache for 30 seconds.
If you click on the button again within 30 seconds, the page is posted back but the label control gets its
information from the cache:
Page Posted Back.
Retrieving test item.
Test item is: 14-07-2010 01:25:04

More Related Content

What's hot

Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state managementpriya Nithya
 
SSMS-waitstats
SSMS-waitstatsSSMS-waitstats
SSMS-waitstatsE Blake
 
Academy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storageAcademy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storageBinary Studio
 
Cloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload CourseCloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload Coursecloudbase.io
 
Document validation in MongoDB 3.2
Document validation in MongoDB 3.2Document validation in MongoDB 3.2
Document validation in MongoDB 3.2Andrew Morgan
 
Asp.net server control
Asp.net  server controlAsp.net  server control
Asp.net server controlSireesh K
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKitTaras Kalapun
 
Windows 8 metro applications
Windows 8 metro applicationsWindows 8 metro applications
Windows 8 metro applicationsAlex Golesh
 
Data Management 3: Bulletproof Data Management
Data Management 3: Bulletproof Data ManagementData Management 3: Bulletproof Data Management
Data Management 3: Bulletproof Data ManagementMongoDB
 
Engage 2013 - Why Upgrade to v10 Tag
Engage 2013 - Why Upgrade to v10 TagEngage 2013 - Why Upgrade to v10 Tag
Engage 2013 - Why Upgrade to v10 TagWebtrends
 
OUG Scotland 2014 - NoSQL and MySQL - The best of both worlds
OUG Scotland 2014 - NoSQL and MySQL - The best of both worldsOUG Scotland 2014 - NoSQL and MySQL - The best of both worlds
OUG Scotland 2014 - NoSQL and MySQL - The best of both worldsAndrew Morgan
 
Joins and Other MongoDB 3.2 Aggregation Enhancements
Joins and Other MongoDB 3.2 Aggregation EnhancementsJoins and Other MongoDB 3.2 Aggregation Enhancements
Joins and Other MongoDB 3.2 Aggregation EnhancementsAndrew Morgan
 

What's hot (20)

Ajax chap 3
Ajax chap 3Ajax chap 3
Ajax chap 3
 
Ajax chap 2.-part 1
Ajax chap 2.-part 1Ajax chap 2.-part 1
Ajax chap 2.-part 1
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
 
Ecom2
Ecom2Ecom2
Ecom2
 
SSMS-waitstats
SSMS-waitstatsSSMS-waitstats
SSMS-waitstats
 
Academy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storageAcademy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storage
 
Cloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload CourseCloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload Course
 
Document validation in MongoDB 3.2
Document validation in MongoDB 3.2Document validation in MongoDB 3.2
Document validation in MongoDB 3.2
 
Asp.net server control
Asp.net  server controlAsp.net  server control
Asp.net server control
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
 
Dandelion 0.10.0
Dandelion 0.10.0Dandelion 0.10.0
Dandelion 0.10.0
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKit
 
Windows 8 metro applications
Windows 8 metro applicationsWindows 8 metro applications
Windows 8 metro applications
 
Ajax chap 4
Ajax chap 4Ajax chap 4
Ajax chap 4
 
Data Management 3: Bulletproof Data Management
Data Management 3: Bulletproof Data ManagementData Management 3: Bulletproof Data Management
Data Management 3: Bulletproof Data Management
 
Ajax chap 5
Ajax chap 5Ajax chap 5
Ajax chap 5
 
Engage 2013 - Why Upgrade to v10 Tag
Engage 2013 - Why Upgrade to v10 TagEngage 2013 - Why Upgrade to v10 Tag
Engage 2013 - Why Upgrade to v10 Tag
 
OUG Scotland 2014 - NoSQL and MySQL - The best of both worlds
OUG Scotland 2014 - NoSQL and MySQL - The best of both worldsOUG Scotland 2014 - NoSQL and MySQL - The best of both worlds
OUG Scotland 2014 - NoSQL and MySQL - The best of both worlds
 
Joins and Other MongoDB 3.2 Aggregation Enhancements
Joins and Other MongoDB 3.2 Aggregation EnhancementsJoins and Other MongoDB 3.2 Aggregation Enhancements
Joins and Other MongoDB 3.2 Aggregation Enhancements
 
OrientDB
OrientDBOrientDB
OrientDB
 

Viewers also liked

Use and reuse
Use and reuseUse and reuse
Use and reuseerm57
 
방황도 힘이 된다 Cnn카페 프로모션 현황
방황도 힘이 된다 Cnn카페 프로모션 현황방황도 힘이 된다 Cnn카페 프로모션 현황
방황도 힘이 된다 Cnn카페 프로모션 현황Munhakdongne
 
천종호 사라지고 살아나고(제1~34회 합본)
천종호 사라지고 살아나고(제1~34회 합본)천종호 사라지고 살아나고(제1~34회 합본)
천종호 사라지고 살아나고(제1~34회 합본)Munhakdongne
 
Net Framework overview
Net Framework overviewNet Framework overview
Net Framework overviewMohitKumar1985
 

Viewers also liked (7)

Use and reuse
Use and reuseUse and reuse
Use and reuse
 
방황도 힘이 된다 Cnn카페 프로모션 현황
방황도 힘이 된다 Cnn카페 프로모션 현황방황도 힘이 된다 Cnn카페 프로모션 현황
방황도 힘이 된다 Cnn카페 프로모션 현황
 
천종호 사라지고 살아나고(제1~34회 합본)
천종호 사라지고 살아나고(제1~34회 합본)천종호 사라지고 살아나고(제1~34회 합본)
천종호 사라지고 살아나고(제1~34회 합본)
 
Asp net
Asp netAsp net
Asp net
 
Web services
Web servicesWeb services
Web services
 
Net Framework overview
Net Framework overviewNet Framework overview
Net Framework overview
 
Sistem ekresi
Sistem ekresiSistem ekresi
Sistem ekresi
 

Similar to Everything You Need to Know About Caching in ASP.NET

C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questionsAkhil Mittal
 
sakdjfhaksjfhaskjh
sakdjfhaksjfhaskjhsakdjfhaksjfhaskjh
sakdjfhaksjfhaskjhelodiaevie
 
askldjfhaskdfj aslkdjfhaskdfhasjk askldf ashkdf
askldjfhaskdfj aslkdjfhaskdfhasjk askldf ashkdfaskldjfhaskdfj aslkdjfhaskdfhasjk askldf ashkdf
askldjfhaskdfj aslkdjfhaskdfhasjk askldf ashkdfelodiaevie
 
salkdjfhdjkghdfkjh
salkdjfhdjkghdfkjhsalkdjfhdjkghdfkjh
salkdjfhdjkghdfkjhelodiaevie
 
aksdfhaskdjfhasdjkh
aksdfhaskdjfhasdjkhaksdfhaskdjfhasdjkh
aksdfhaskdjfhasdjkhelodiaevie
 
State management
State managementState management
State managementIblesoft
 
06 asp.net session08
06 asp.net session0806 asp.net session08
06 asp.net session08Vivek chan
 
Programming web application
Programming web applicationProgramming web application
Programming web applicationaspnet123
 
Chanhao Jiang And David Wei Presentation Quickling Pagecache
Chanhao Jiang And David Wei Presentation Quickling PagecacheChanhao Jiang And David Wei Presentation Quickling Pagecache
Chanhao Jiang And David Wei Presentation Quickling PagecacheAjax Experience 2009
 

Similar to Everything You Need to Know About Caching in ASP.NET (20)

Asp.net
Asp.netAsp.net
Asp.net
 
Aspnet Caching
Aspnet CachingAspnet Caching
Aspnet Caching
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
 
awergaezrg
awergaezrgawergaezrg
awergaezrg
 
sakdjfhaksjfhaskjh
sakdjfhaksjfhaskjhsakdjfhaksjfhaskjh
sakdjfhaksjfhaskjh
 
askldjfhaskdfj aslkdjfhaskdfhasjk askldf ashkdf
askldjfhaskdfj aslkdjfhaskdfhasjk askldf ashkdfaskldjfhaskdfj aslkdjfhaskdfhasjk askldf ashkdf
askldjfhaskdfj aslkdjfhaskdfhasjk askldf ashkdf
 
sergaerwga
sergaerwgasergaerwga
sergaerwga
 
salkdjfhdjkghdfkjh
salkdjfhdjkghdfkjhsalkdjfhdjkghdfkjh
salkdjfhdjkghdfkjh
 
aergserga
aergsergaaergserga
aergserga
 
aksdfhaskdjfhasdjkh
aksdfhaskdjfhasdjkhaksdfhaskdjfhasdjkh
aksdfhaskdjfhasdjkh
 
State management
State managementState management
State management
 
Asp.net
Asp.netAsp.net
Asp.net
 
catching in c#.pptx
catching in c#.pptxcatching in c#.pptx
catching in c#.pptx
 
Managing states
Managing statesManaging states
Managing states
 
2310 b 15
2310 b 152310 b 15
2310 b 15
 
2310 b 15
2310 b 152310 b 15
2310 b 15
 
Ror caching
Ror cachingRor caching
Ror caching
 
06 asp.net session08
06 asp.net session0806 asp.net session08
06 asp.net session08
 
Programming web application
Programming web applicationProgramming web application
Programming web application
 
Chanhao Jiang And David Wei Presentation Quickling Pagecache
Chanhao Jiang And David Wei Presentation Quickling PagecacheChanhao Jiang And David Wei Presentation Quickling Pagecache
Chanhao Jiang And David Wei Presentation Quickling Pagecache
 

More from MohitKumar1985

More from MohitKumar1985 (8)

Html interview-questions-and-answers
Html interview-questions-and-answersHtml interview-questions-and-answers
Html interview-questions-and-answers
 
Caching in asp.net
Caching in asp.netCaching in asp.net
Caching in asp.net
 
Asp net
Asp netAsp net
Asp net
 
Sql queires
Sql queiresSql queires
Sql queires
 
Webservices
WebservicesWebservices
Webservices
 
C# Collection classes
C# Collection classesC# Collection classes
C# Collection classes
 
Interview Question of Aspdotnet
Interview Question of AspdotnetInterview Question of Aspdotnet
Interview Question of Aspdotnet
 
Matrimonial
MatrimonialMatrimonial
Matrimonial
 

Recently uploaded

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 

Recently uploaded (20)

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 

Everything You Need to Know About Caching in ASP.NET

  • 1. What is Caching? 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 places frequently used data in quickly accessed media like the random access memory of the computer. The ASP.Net runtime includes a key-value map of CLR objects called cache. This lives with the application and is available via the HttpContext and System.Web.UI.Page. In some respect, caching is similar to storing the state objects. However, the storing information in state objects is deterministic, i.e., you can count on the data being stored there, and caching of data is nondeterministic. The data will not be available if its lifetime expires, or the application releases its memory, or caching does not take place for some reason. You can access items in the cache using an indexer and may control the lifetime of objects in the cache and set up links between the cached objects and their physical sources. Caching in ASP.Net: ASP.Net provides the following different types of caching:  Output Caching: Output cache stores a copy of the finally rendered HTML pages or part of pages sent to the client. When the next client requests for this page, instead of regenerating the page, a cached copy of the page is sent, thus saving time.  Data Caching: 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.  Object Caching: Object caching is caching the objects on a page, such as data-bound controls. The cached data is stored in server memory.  Class Caching: Web pages or web services are compiled into a page class in the assembly, when run for the first time. Then the assembly is cached in the server. Next time when a request is made for the page or service, the cached assembly is referred to. When the source code is changed, the CLR recompiles the assembly.  Configuration Caching: Application wide configuration information is stored in a configuration file. Configuration caching stores the configuration information in the server memory. Output Caching: Rendering a page may involve some complex processes like, database access, rendering complex controls etc. Output caching allows bypassing the round trips to server by caching data in memory. Even the whole page could be cached. The OutputCache directive is responsible of output caching. It enables output caching and provides certain control over its behaviour. Syntax for OutputCache directive: <%@ OutputCache Duration="15" VaryByParam="None" %> Put this directive under the page directive . This tells the environment to cache the page for 15 seconds. The following event handler for page load would help in testing that the page was really cached. protected void Page_Load(object sender, EventArgs e) { Thread.Sleep(10000); Response.Write("This page was generated and cache at:" +
  • 2. DateTime.Now.ToString()); } The Thread.Sleep() method stops the process thread for the specified time. In this example, the thread is stopped for 10 seconds, so when the page is loaded for first time, it will take 10 seconds. But next time you refresh the page, it does not take any time, as the page will retrieved from the cache without being loaded. The OutputCache directive has the following attributes, which helps in controlling the behaviour of the output cache: Attribute Values Description DiskCacheable true/false Specifies that output could be written to a disk based cache. NoStore true/false Specifies that the "no store" cache control header is sent or not. CacheProfile String name Name of a cache profile as to be stored in web.config. VaryByParam None * Param- name Semicolon delimited list of string specifies query string values in a GET request or variable in a POST request. VaryByHeader * Header names Semicolon delimited list of strings specifying headers that might be submitted by a client. VaryByCustom Browser Custom string Tells ASP.Net to vary the output cache by browser name and version or by a custom string. Location Any Client Downstream Server None Any: page may be cached anywhere. Client: cached content remains at browser. Downstream: cached content stored in downstream and server both. Server: cached content saved only on server. None: disables caching. Duration Number Number of seconds the page or control is cached. Let us add a text box and a button to the previous example and add this event handler for the button. protected void btnmagic_Click(object sender, EventArgs e) { Response.Write("<br><br>"); Response.Write("<h2> Hello, " + this.txtname.Text + "</h2>"); } And change the OutputCache directive : <%@ OutputCache Duration="60" VaryByParam="txtname" %> When the program is executed, ASP.Net caches the page on the basis of the name in the text box.
  • 3. OutputCache - varybycontrol The varybycontrol does exactly what it says - it varies the cache depending on the value of the specified control. For instance, you can have a dropdownlist with a set of selections, and base the content of the page based on the selected item. In that case, it will make sense to vary by the value of this control, since the content of the page changes according to it. Here is an example of using the varybycontrol parameter: <%@ OutputCache duration="10" varybyparam="none" varybycontrol="NameOfControl" %> OutputCache - varybycustom This is probably the least easy way of using the OutputCache system, but on the other hand, probably the most flexible. It allows you to handle the variations your self, by setting a custom string, which ASP.NET will vary the output by. To test this, you need to add a global.asax file to your project, if you don't already have one. Right click on your project in the Solution Explorer, and select Add new item. Now select the "Global Application Class" and click Ok. In the Global.asax file, you need to override the GetVaryByCustomString like this: public override string GetVaryByCustomString(HttpContext context, string custom) { if(custom == "Browser") { return context.Request.Browser.Browser; } return String.Empty; } In this case, our caching will be varied based on which browser the user accesses the page with. The markup part should be written like this: <%@ OutputCache duration="120" varybyparam="None" varybycustom="Browser" %> Try accessing the page from different browsers. You will see that the output now depends on which browser you use. The Browser object comes with a bunch of useful information about the client browser - for instance you could vary by whether or not the browser supports CSS, JavaScript or something else. OutputCache - varybyheader This one allows you to vary the content based on one or more of the headers that browser send. Here is an example: <%@ OutputCache duration="120" varybyparam="None" varybyheader="Accept-Language" %> This will vary cache based on the Accept-Language header, which tells the server which languages the user accepts and prefers. Data Caching: The main aspect of data caching is caching the data source controls. We have already discussed that the data source controls represent data in a data source, like a database or an XML file. These controls derive from the abstract class DataSourceControl and have the following inherited properties for implementing caching:  CacheDuration - sets the number of seconds for which the data source will cache data  CacheExpirationPolicy - defines the cache behaviour when the data in cache has expired  CacheKeyDependency - identifies a key for the controls that auto-expires the content of its cache when removed  EnableCaching - specifies whether or not to cache data Example:
  • 4. To demonstrate data caching, create a new website and add a new web form in it. Add to it a SqlDataSource control with the database connection already used in the data access tutorials. For this example, add a label to the page, which would show the response time for the page. <asp:Label ID="lbltime" runat="server"></asp:Label> Apart from the label, the content page is same as in the data access tutorial. Add an event handler for the page load event: protected void Page_Load(object sender, EventArgs e) { lbltime.Text = String.Format("Page posted at: {0}", DateTime.Now.ToLongTimeString()); } The design page should look like the following: When you run the page for the first time, nothing different happens, the label shows that, each time you refresh the page, the page is reloaded and the time shown on the label changes. Next, set the EnableCaching attribute of the data source control to be 'true' and set the Cacheduration attribute to '60'. It will implement caching and the cache will expire every 60 seconds. Now the timestamp will change with every refresh, but if you change the data in the table within these 60 seconds, it won't show before the cache expires: <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings: ASPDotNetStepByStepConnectionString %>" ProviderName="<%$ ConnectionStrings: ASPDotNetStepByStepConnectionString.ProviderName %>" SelectCommand="SELECT * FROM [DotNetReferences]" EnableCaching="true" CacheDuration = "60"> </asp:SqlDataSource> Object Caching: Object caching provides more flexibility than other cache techniques. You can use object caching to place any object in the cache. The object can be of any type - a data type, a web control, a class, a DataSet object, etc. The item is added to the cache simply by assigning a new key name. Like: Cache["key"] = item;
  • 5. ASP.Net also provides the Insert() method for inserting an object to the cache. This method has four overloaded versions. Let us see the various versions first. Overload Description Cache.Insert((key, value); Inserts an item into the cache with the key name and value with default priority and expiration. Cache.Insert(key, value, dependencies); Inserts an item into the cache with key, value, default priority, expiration and a CacheDependency name that links to other files or items so that when these change the cache item remains no longer valid. Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration); This indicates an expiration policy along with the above issues. Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); This along with the parameters also allows you to set a priority for the cache item and a delegate that, points to a method to be invoked when the item is removed. Sliding expiration is used to remove an item from the cache when it is not used for the specified time span. The following code snippet stores an item with a sliding expiration of 10 minutes with no dependencies. Cache.Insert("my_item", obj, null, DateTime.MaxValue, TimeSpan.FromMinutes(10)); Example: Create a page with just a button and a label. Write the following code in the page load event: protected void Page_Load(object sender, EventArgs e) { if (this.IsPostBack) { lblinfo.Text += "Page Posted Back.<br/>"; } else { lblinfo.Text += "page Created.<br/>"; } if (Cache["testitem"] == null) { lblinfo.Text += "Creating test item.<br/>"; DateTime testItem = DateTime.Now;
  • 6. lblinfo.Text += "Storing test item in cache "; lblinfo.Text += "for 30 seconds.<br/>"; Cache.Insert("testitem", testItem, null, DateTime.Now.AddSeconds(30), TimeSpan.Zero); } else { lblinfo.Text += "Retrieving test item.<br/>"; DateTime testItem = (DateTime)Cache["testitem"]; lblinfo.Text += "Test item is: " + testItem.ToString(); lblinfo.Text += "<br/>"; } lblinfo.Text += "<br/>"; } When the page is loaded for the first time it says: Page Created. Creating test item. Storing test item in cache for 30 seconds. If you click on the button again within 30 seconds, the page is posted back but the label control gets its information from the cache: Page Posted Back. Retrieving test item. Test item is: 14-07-2010 01:25:04