SlideShare uma empresa Scribd logo
1 de 19
• What is Caching
• When to use Caching
• Types of Caching
   • Output Caching
      • QueryString and Profile Caching
   • Data Caching
      • Simple, Dataset and DataSource Caching
• Cache Dependencies
   • File / Item / DataBase Dependencies
Caching is the process of storing frequently used data,
usually data that is costly to generate, for reuse.

Typically this data is stored in memory since retrieving
data from memory is much more efficient than retrieving
the data from other locations, such as a database or a file.

When you store information in a cache the lifetime of that
information is at the discretion of the server. If the cache
becomes full or other applications consume a large
amount of memory, data will be selectively evicted from the
cache, ensuring that the application continues to perform
well.
A good caching strategy identifies the most frequently
used pieces of data that are the most time-consuming to
create and stores them. If you store too much
information, you risk filling up the cache with relatively
unimportant data and forcing out the content you really
want to keep.

Cache data (or web pages) that are expensive: The
results of a database query or contents of a file.

Cache data (or web pages) that are used frequently: The
list of product categories instead of product detail pages.
ASP.NET really has two types of caching.

Output caching: It stores a copy of the final rendered
HTML page that is sent to the client. The next client that
submits a request for this page doesn’t actually run the
page. Instead, the final HTML output is sent automatically.

Data caching: This is carried out manually in your code.
To use data caching, you store important pieces of
information that are time-consuming to reconstruct (such
as a DataSet retrieved from a database) in the cache.
Other pages can check for the existence of this
information and use it, thereby bypassing the steps
ordinarily required to retrieve it.
With output caching, the final rendered HTML of the page
is cached. When the same page is requested again, the
control objects are not created, the page life cycle doesn’t
start, and none of your code executes. Instead, the
cached HTML is served.

You can cache an ASP.NET page in two ways.

Insert the OutputCache directive at the top of your .aspx
file, just below the Page directive
<%@ OutputCache Duration="20" VaryByParam="None" %>
Cache the page exclusively on the client side
<%@ OutputCache Duration="20" VaryByParam="None"
Location="Client" %>
When you request the page with additional query string
information, ASP.NET will examine the query string. If the
string matches a previous request and a cached copy of
that page exists, it will be reused. Otherwise, a new copy
of the page will be created and cached separately.

You can set the VaryByParam attribute to * to indicate that
the page uses the query string and to instruct ASP.NET to
cache separate copies of the page for different query
string arguments:
<%@ OutputCache Duration="20" VaryByParam="*" %>
Or
<%@ OutputCache Duration="20“
VaryByParam="ProductID;CurrencyType" %>
ASP.NET includes a feature called cache profiles that
makes it easy to apply the same caching settings to a
group of pages.

With cache profiles, you define a group of caching settings
in the web.config file, associate a name with these
settings, and then apply these settings to multiple pages
using the name.

That way, you have the freedom to modify all the linked
pages at once simply by changing the caching profile in
the web.config file.
To define a cache profile, you use the <add> tag in the
<outputCacheProfiles> section, as follows.

<configuration>
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="ProductItemCacheProfile" duration="60" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
...
</system.web>
</configuration>
You can now use this profile in a page through the CacheProfile
attribute:

<%@ OutputCache CacheProfile="ProductItemCacheProfile"
VaryByParam="None" %>
The basic principle of data caching is that you add items
that are expensive to create to a built-in collection object
called Cache.

Cache is a property of the Page class, and it returns an
instance of the System.Web.Caching.Cache class.

You can insert an object into the cache in several ways.

1. Cache["KeyName"] = objectToCache;

2. Cache.Insert(key, item, dependencies, absoluteExpira
   tion, slidingExpiration);
Absolute expirations are best when you know the
information in a given item can be considered
valid only for a specific amount of time (such as a stock
chart or a weather report).

Sliding expiration, on the other hand, is more useful
when you know that a cached item will always remain
valid (such as with historical data or a product catalog)
but should still be allowed to expire if it isn’t being
used.
You cannot set both a sliding expiration and an
absolute expiration policy at the same time. If you want
to use an absolute expiration, set the slidingExpiration
parameter to TimeSpan.Zero

Cache.Insert("MyItem", obj, null,
DateTime.Now.AddMinutes(60), TimeSpan.Zero);


To set a sliding expiration policy, set the
absoluteExpiration parameter to DateTime.MaxValue

Cache.Insert("MyItem", obj, null,
DateTime.MaxValue, TimeSpan.FromMinutes(10));
private DataSet RetrieveData()
{
string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].Connection
String;
string SQLSelect = "SELECT * FROM Customers";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(SQLSelect, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
con.Open();
adapter.Fill(ds, "Customers");
}
finally
{
con.Close();
}
return ds;
}
private DataSet GetDataSet()
{
DataSet ds = (DataSet)Cache["Customers"];
// Contact the database if necessary.
if (ds == null)
{
ds = RetrieveData();
Cache.Insert("Customers", ds, null, DateTime.MaxValue,
TimeSpan.FromMinutes(2));
lblCacheStatus.Text = "Created and added to cache.";
}
else
{
lblCacheStatus.Text = "Retrieved from cache.";
}
return ds;
}
The SqlDataSource and ObjectDataSource support built-in data caching.
Using caching with these controls is highly recommended, because they
can be more inefficient than handwritten data access code.

Caching Properties of the Data Source Controls
As time passes, the information in your data source may
change. If your code uses caching, you may remain
unaware of the changes and continue using out-of-date
information from the cache.

To help mitigate this problem, ASP.NET supports cache
dependencies. Cache dependencies allow you to make a
cached item dependent on another resource, so that when
that resource changes, the cached item is removed
automatically.

ASP.NET includes three types of dependencies:
• Dependencies on files or folders
• Dependencies on other cached items
• Dependencies on a database query
To use a cache dependency, you need to create a CacheDependency
object. You then need to supply the CacheDependency object when
you add the dependent cached item.

For example, the following code creates a CacheDependency that
Create a CacheDependency that depends on an XML file named
ProductList.xml. When the XML file is changed, the
CacheDependency will be invalidated, and the dependent cached
item will be evicted from the cache immediately.

Dim dom As XmlDocument()
dom.Load(Server.MapPath("ProductList..xml")
Cache(“prodInfo") = dom

CacheDependency prodDependency = new CacheDependency(
Server.MapPath("ProductList.xml"));

Cache.Insert("ProductInfo", prodInfo, prodDependency);
Cache["Key1"] = "Cache Item 1";

// Make Cache["Key2"] dependent on Cache["Key1"]

string[] dependencyKey = new string[1];

dependencyKey[0] = "Key1";

CacheDependency dependency = new CacheDependency(null,
dependencyKey);

Cache.Insert("Key2", "Cache Item 2", dependency);
string connectionString = WebConfigurationManager.ConnectionStrings[
"Northwind"].ConnectionString;
SqlDependency.Start(connectionString)

SqlConnection con = new SqlConnection(connectionString);
string query =
"SELECT EmployeeID, FirstName, LastName, City FROM dbo.Employees";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);

// Fill the DataSet.
DataSet ds = new DataSet();
adapter.Fill(ds, "Employees");

// Create the dependency.
SqlCacheDependency empDependency = new SqlCacheDependency(cmd);

Cache.Insert("Employees", ds, empDependency);

Mais conteúdo relacionado

Mais procurados

Data Binding in Silverlight
Data Binding in SilverlightData Binding in Silverlight
Data Binding in SilverlightBoulos Dib
 
MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018Dave Stokes
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationRandy Connolly
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentalsMadhuri Kavade
 
Develop PHP Applications with MySQL X DevAPI
Develop PHP Applications with MySQL X DevAPIDevelop PHP Applications with MySQL X DevAPI
Develop PHP Applications with MySQL X DevAPIDave Stokes
 
FITC presents: Mobile & offline data synchronization in Angular JS
FITC presents: Mobile & offline data synchronization in Angular JSFITC presents: Mobile & offline data synchronization in Angular JS
FITC presents: Mobile & offline data synchronization in Angular JSFITC
 
Electron, databases, and RxDB
Electron, databases, and RxDBElectron, databases, and RxDB
Electron, databases, and RxDBBen Gotow
 
Document validation in MongoDB 3.2
Document validation in MongoDB 3.2Document validation in MongoDB 3.2
Document validation in MongoDB 3.2Andrew Morgan
 
Adf walkthrough
Adf walkthroughAdf walkthrough
Adf walkthroughMSDEVMTL
 
SQL Server Extended Events presentation from SQL Midlands User Group 14th Mar...
SQL Server Extended Events presentation from SQL Midlands User Group 14th Mar...SQL Server Extended Events presentation from SQL Midlands User Group 14th Mar...
SQL Server Extended Events presentation from SQL Midlands User Group 14th Mar...Stuart Moore
 
07 darwino rest services
07   darwino rest services07   darwino rest services
07 darwino rest servicesdarwinodb
 
SQL Server Extended Events
SQL Server Extended Events SQL Server Extended Events
SQL Server Extended Events Stuart Moore
 
State management 1
State management 1State management 1
State management 1singhadarsh
 
CouchDB : More Couch
CouchDB : More CouchCouchDB : More Couch
CouchDB : More Couchdelagoya
 

Mais procurados (20)

Data Binding in Silverlight
Data Binding in SilverlightData Binding in Silverlight
Data Binding in Silverlight
 
MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018MySQL 8 Server Optimization Swanseacon 2018
MySQL 8 Server Optimization Swanseacon 2018
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
Develop PHP Applications with MySQL X DevAPI
Develop PHP Applications with MySQL X DevAPIDevelop PHP Applications with MySQL X DevAPI
Develop PHP Applications with MySQL X DevAPI
 
Sql data shrink steps
Sql data shrink stepsSql data shrink steps
Sql data shrink steps
 
FITC presents: Mobile & offline data synchronization in Angular JS
FITC presents: Mobile & offline data synchronization in Angular JSFITC presents: Mobile & offline data synchronization in Angular JS
FITC presents: Mobile & offline data synchronization in Angular JS
 
Data Binding
Data BindingData Binding
Data Binding
 
Core Java tutorial at Unit Nexus
Core Java tutorial at Unit NexusCore Java tutorial at Unit Nexus
Core Java tutorial at Unit Nexus
 
Electron, databases, and RxDB
Electron, databases, and RxDBElectron, databases, and RxDB
Electron, databases, and RxDB
 
Document validation in MongoDB 3.2
Document validation in MongoDB 3.2Document validation in MongoDB 3.2
Document validation in MongoDB 3.2
 
Adf walkthrough
Adf walkthroughAdf walkthrough
Adf walkthrough
 
For Beginers - ADO.Net
For Beginers - ADO.NetFor Beginers - ADO.Net
For Beginers - ADO.Net
 
SQL Server Extended Events presentation from SQL Midlands User Group 14th Mar...
SQL Server Extended Events presentation from SQL Midlands User Group 14th Mar...SQL Server Extended Events presentation from SQL Midlands User Group 14th Mar...
SQL Server Extended Events presentation from SQL Midlands User Group 14th Mar...
 
07 darwino rest services
07   darwino rest services07   darwino rest services
07 darwino rest services
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
SQL Server Extended Events
SQL Server Extended Events SQL Server Extended Events
SQL Server Extended Events
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
State management 1
State management 1State management 1
State management 1
 
CouchDB : More Couch
CouchDB : More CouchCouchDB : More Couch
CouchDB : More Couch
 

Destaque (8)

Chapter 25
Chapter 25Chapter 25
Chapter 25
 
Next step job board (Assignment)
Next step job board (Assignment)Next step job board (Assignment)
Next step job board (Assignment)
 
Chapter 19
Chapter 19Chapter 19
Chapter 19
 
Chapter 26
Chapter 26Chapter 26
Chapter 26
 
C# question answers
C# question answersC# question answers
C# question answers
 
Assignment
AssignmentAssignment
Assignment
 
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
 
C# interview questions
C# interview questionsC# interview questions
C# interview questions
 

Semelhante a Chapter 23

Semelhante a Chapter 23 (20)

Caching in asp.net
Caching in asp.netCaching in asp.net
Caching in asp.net
 
Aspnet Caching
Aspnet CachingAspnet Caching
Aspnet Caching
 
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
 
Asp.net
Asp.netAsp.net
Asp.net
 
Caching in Kentico 11
Caching in Kentico 11Caching in Kentico 11
Caching in Kentico 11
 
Ror caching
Ror cachingRor caching
Ror caching
 
catching in c#.pptx
catching in c#.pptxcatching in c#.pptx
catching in c#.pptx
 
Academy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storageAcademy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storage
 
Html5三种本地存储方式的比较
Html5三种本地存储方式的比较Html5三种本地存储方式的比较
Html5三种本地存储方式的比较
 
Cache
CacheCache
Cache
 
Asp.net c# MVC-5 Training-Day-2 of Day-9
Asp.net c# MVC-5 Training-Day-2 of Day-9Asp.net c# MVC-5 Training-Day-2 of Day-9
Asp.net c# MVC-5 Training-Day-2 of Day-9
 
2310 b 15
2310 b 152310 b 15
2310 b 15
 
2310 b 15
2310 b 152310 b 15
2310 b 15
 
Chapter 8 part1
Chapter 8   part1Chapter 8   part1
Chapter 8 part1
 

Mais de application developer (20)

Chapter 18
Chapter 18Chapter 18
Chapter 18
 
Chapter 17
Chapter 17Chapter 17
Chapter 17
 
Chapter 16
Chapter 16Chapter 16
Chapter 16
 
Week 3 assignment
Week 3 assignmentWeek 3 assignment
Week 3 assignment
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
Chapter 13
Chapter 13Chapter 13
Chapter 13
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
 
Chapter 11
Chapter 11Chapter 11
Chapter 11
 
Chapter 10
Chapter 10Chapter 10
Chapter 10
 
C # test paper
C # test paperC # test paper
C # test paper
 
Chapter 9
Chapter 9Chapter 9
Chapter 9
 
Chapter 8 part2
Chapter 8   part2Chapter 8   part2
Chapter 8 part2
 
Chapter 7
Chapter 7Chapter 7
Chapter 7
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Week 1 Assignment Q2 Solution
Week 1 Assignment Q2 SolutionWeek 1 Assignment Q2 Solution
Week 1 Assignment Q2 Solution
 
Week 1 assignment q2
Week 1 assignment q2Week 1 assignment q2
Week 1 assignment q2
 
Week 1 Assignment Q1 Solution
Week 1 Assignment Q1 SolutionWeek 1 Assignment Q1 Solution
Week 1 Assignment Q1 Solution
 
C# for beginners
C# for beginnersC# for beginners
C# for beginners
 

Último

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
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
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
"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
 
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
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
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
 
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
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
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
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Último (20)

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
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!
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
"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
 
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
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
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
 
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
 
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
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
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
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

Chapter 23

  • 1. • What is Caching • When to use Caching • Types of Caching • Output Caching • QueryString and Profile Caching • Data Caching • Simple, Dataset and DataSource Caching • Cache Dependencies • File / Item / DataBase Dependencies
  • 2. Caching is the process of storing frequently used data, usually data that is costly to generate, for reuse. Typically this data is stored in memory since retrieving data from memory is much more efficient than retrieving the data from other locations, such as a database or a file. When you store information in a cache the lifetime of that information is at the discretion of the server. If the cache becomes full or other applications consume a large amount of memory, data will be selectively evicted from the cache, ensuring that the application continues to perform well.
  • 3. A good caching strategy identifies the most frequently used pieces of data that are the most time-consuming to create and stores them. If you store too much information, you risk filling up the cache with relatively unimportant data and forcing out the content you really want to keep. Cache data (or web pages) that are expensive: The results of a database query or contents of a file. Cache data (or web pages) that are used frequently: The list of product categories instead of product detail pages.
  • 4. ASP.NET really has two types of caching. Output caching: It stores a copy of the final rendered HTML page that is sent to the client. The next client that submits a request for this page doesn’t actually run the page. Instead, the final HTML output is sent automatically. Data caching: This is carried out manually in your code. To use data caching, you store important pieces of information that are time-consuming to reconstruct (such as a DataSet retrieved from a database) in the cache. Other pages can check for the existence of this information and use it, thereby bypassing the steps ordinarily required to retrieve it.
  • 5. With output caching, the final rendered HTML of the page is cached. When the same page is requested again, the control objects are not created, the page life cycle doesn’t start, and none of your code executes. Instead, the cached HTML is served. You can cache an ASP.NET page in two ways. Insert the OutputCache directive at the top of your .aspx file, just below the Page directive <%@ OutputCache Duration="20" VaryByParam="None" %> Cache the page exclusively on the client side <%@ OutputCache Duration="20" VaryByParam="None" Location="Client" %>
  • 6. When you request the page with additional query string information, ASP.NET will examine the query string. If the string matches a previous request and a cached copy of that page exists, it will be reused. Otherwise, a new copy of the page will be created and cached separately. You can set the VaryByParam attribute to * to indicate that the page uses the query string and to instruct ASP.NET to cache separate copies of the page for different query string arguments: <%@ OutputCache Duration="20" VaryByParam="*" %> Or <%@ OutputCache Duration="20“ VaryByParam="ProductID;CurrencyType" %>
  • 7. ASP.NET includes a feature called cache profiles that makes it easy to apply the same caching settings to a group of pages. With cache profiles, you define a group of caching settings in the web.config file, associate a name with these settings, and then apply these settings to multiple pages using the name. That way, you have the freedom to modify all the linked pages at once simply by changing the caching profile in the web.config file.
  • 8. To define a cache profile, you use the <add> tag in the <outputCacheProfiles> section, as follows. <configuration> <system.web> <caching> <outputCacheSettings> <outputCacheProfiles> <add name="ProductItemCacheProfile" duration="60" /> </outputCacheProfiles> </outputCacheSettings> </caching> ... </system.web> </configuration> You can now use this profile in a page through the CacheProfile attribute: <%@ OutputCache CacheProfile="ProductItemCacheProfile" VaryByParam="None" %>
  • 9. The basic principle of data caching is that you add items that are expensive to create to a built-in collection object called Cache. Cache is a property of the Page class, and it returns an instance of the System.Web.Caching.Cache class. You can insert an object into the cache in several ways. 1. Cache["KeyName"] = objectToCache; 2. Cache.Insert(key, item, dependencies, absoluteExpira tion, slidingExpiration);
  • 10.
  • 11. Absolute expirations are best when you know the information in a given item can be considered valid only for a specific amount of time (such as a stock chart or a weather report). Sliding expiration, on the other hand, is more useful when you know that a cached item will always remain valid (such as with historical data or a product catalog) but should still be allowed to expire if it isn’t being used.
  • 12. You cannot set both a sliding expiration and an absolute expiration policy at the same time. If you want to use an absolute expiration, set the slidingExpiration parameter to TimeSpan.Zero Cache.Insert("MyItem", obj, null, DateTime.Now.AddMinutes(60), TimeSpan.Zero); To set a sliding expiration policy, set the absoluteExpiration parameter to DateTime.MaxValue Cache.Insert("MyItem", obj, null, DateTime.MaxValue, TimeSpan.FromMinutes(10));
  • 13. private DataSet RetrieveData() { string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].Connection String; string SQLSelect = "SELECT * FROM Customers"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(SQLSelect, con); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); try { con.Open(); adapter.Fill(ds, "Customers"); } finally { con.Close(); } return ds; }
  • 14. private DataSet GetDataSet() { DataSet ds = (DataSet)Cache["Customers"]; // Contact the database if necessary. if (ds == null) { ds = RetrieveData(); Cache.Insert("Customers", ds, null, DateTime.MaxValue, TimeSpan.FromMinutes(2)); lblCacheStatus.Text = "Created and added to cache."; } else { lblCacheStatus.Text = "Retrieved from cache."; } return ds; }
  • 15. The SqlDataSource and ObjectDataSource support built-in data caching. Using caching with these controls is highly recommended, because they can be more inefficient than handwritten data access code. Caching Properties of the Data Source Controls
  • 16. As time passes, the information in your data source may change. If your code uses caching, you may remain unaware of the changes and continue using out-of-date information from the cache. To help mitigate this problem, ASP.NET supports cache dependencies. Cache dependencies allow you to make a cached item dependent on another resource, so that when that resource changes, the cached item is removed automatically. ASP.NET includes three types of dependencies: • Dependencies on files or folders • Dependencies on other cached items • Dependencies on a database query
  • 17. To use a cache dependency, you need to create a CacheDependency object. You then need to supply the CacheDependency object when you add the dependent cached item. For example, the following code creates a CacheDependency that Create a CacheDependency that depends on an XML file named ProductList.xml. When the XML file is changed, the CacheDependency will be invalidated, and the dependent cached item will be evicted from the cache immediately. Dim dom As XmlDocument() dom.Load(Server.MapPath("ProductList..xml") Cache(“prodInfo") = dom CacheDependency prodDependency = new CacheDependency( Server.MapPath("ProductList.xml")); Cache.Insert("ProductInfo", prodInfo, prodDependency);
  • 18. Cache["Key1"] = "Cache Item 1"; // Make Cache["Key2"] dependent on Cache["Key1"] string[] dependencyKey = new string[1]; dependencyKey[0] = "Key1"; CacheDependency dependency = new CacheDependency(null, dependencyKey); Cache.Insert("Key2", "Cache Item 2", dependency);
  • 19. string connectionString = WebConfigurationManager.ConnectionStrings[ "Northwind"].ConnectionString; SqlDependency.Start(connectionString) SqlConnection con = new SqlConnection(connectionString); string query = "SELECT EmployeeID, FirstName, LastName, City FROM dbo.Employees"; SqlCommand cmd = new SqlCommand(query, con); SqlDataAdapter adapter = new SqlDataAdapter(cmd); // Fill the DataSet. DataSet ds = new DataSet(); adapter.Fill(ds, "Employees"); // Create the dependency. SqlCacheDependency empDependency = new SqlCacheDependency(cmd); Cache.Insert("Employees", ds, empDependency);