Sie sind auf Seite 1von 9

Data caching in ASP.

Net applications
In ths post I w contnue my seres of posts on cachng.
You can read my other post n Output caching here.You can read on how to cache a page dependng on the user's browser anguage.
Output cachng has ts pace as a cachng mechansm. But rght now I w focus on data cachng.The advantages of data cachng are we known but I w hghght the man ponts.
We have mprovements n response tmes
We have reduced database round trps
We have dfferent eves of cachng and t s up to us as deveopers to use the approprate one
I w demonstrate data cachng wth a hands on exampe.Embrace yourseves for a very ong post.
I assume that you have access to a verson of SQL Server and Northwind database.
If you do not, you can downoad and nsta the free SQL Server Express edton from here. If you need the nstaaton scrpts for the sampe Northwnd database, cck here
1) Launch Vsua Studo 2010/2008/2005 (express edtons w work fne). Create a new empty webste and choose a sutabe name for t. Choose C# as the deveopment anguage.
2) Add a new tem to your ste, a web form. Leave the defaut name, Deault.aspx
3) Add ASP.Net foder n your ste, App!Code. Add another tem n your fe, a cass fe and ca t DataAccess.cs.Add a namespace n the same cass fe and name t Caching.
4) Go to "iew # $ Server Explorer (Database Exporer) and add a connecton to theNorthwind database.You have |ust to set the nstance of the SOL Server and the name of the
database.Test the connecton.
5) In your we%.conig (whch s pretty much empty) add a &connectionStrings$secton. In my case t ke the one beow. In your case you must set the Data Source property to your
SOL server nstance.
<connectonStrngs> <add name="NorthwndConnectonStrng"connectonStrng="Data
Source=USER-PC\SOLEXPRESS;Inta Cataog=Northwnd;Integrated
Securty=True"provderName="System.Data.SqCent"/>
</connectonStrngs>
6) My ntenton s to popuate a datatabe ob|ect wtn some data from the Custo'ers tabe
from the Northwnd database.I w create a statc method nsde the statc cass.
Insde my DataAccess.cs fe I have ths code so far
namespace Cachng
{
pubc statc cass DataAcess
{
pubc statc DataTabe GetCustomers()
{
strng conn =ConfguratonManager.ConnectonStrngs|"NorthwndConnectonStrng"|.
ConnectonStrng;
SqDataAdapter adapt = new SqDataAdapter("seect top 10 * from customers order by
country", conn);
DataTabe mydatatabe = new DataTabe();
adapt.F(mydatatabe);
return mydatatabe;
}
}
}
Ths s very smpe statc method. It returns a Datatabe ob|ect as ntented.Insde ths method I do the foowng,
I get the connecton strng from the confguraton fe
I create a new adapter ob|ect by passng n as parameters, the SOL statement and the connecton strng
I create a new DataTabe ob|ect and f t n wth data by cang the (ill method of the adapter ob|ect.
7) Make sure you have added the foowng usng statements at the begnnng of the fe.
usng System.Data;
usng System.Data.SqCent;
usng System.Confguraton;
8) Add a )ridview and an O%*ectDatasource contro on the form.Leave the defaut
names. Set the DataSource+D of the )rid"iew to O%*ectDataSource,.
Confgure the O%*ectDatasource contro to seect as the Select method
the)etCusto'ers-. method of the DataAccess cass.The markup for ths specf contro
shoud ook ke ths. <asp:Ob|ectDataSource ID="Ob|ectDataSource1" runat="server"
SeectMethod="GetCustomers" TypeName="Cachng.DataAcess">
</asp:Ob|ectDataSource>
9) Run your appcaton and you w see the returnng rows dspayed to the database.So far
we have done nothng regardng cachng. We |ust ad down the foundaton.
10) We w make some changes n our )etCusto'ers-. method to ncorporate cachng.
namespace Cachng
{
pubc statc cass DataAcess
{
pubc statc DataTabe GetCustomers()
{
DataTabe mydatatabe = nu;f (HttpContext.Current.Cache|"customers"| ==nu)
{
strng conn =ConfguratonManager.ConnectonStrngs|"NorthwndConnectonStrng"|.
ConnectonStrng;
SqDataAdapter adapt = new SqDataAdapter("seect top 10 * from customers order by
country", conn);mydatatabe = new DataTabe();
adapt.F(mydatatabe);
HttpContext.Current.Cache|"customers"| = mydatatabe;
}
ese
mydatatabe = HttpContext.Current.Cache|"customers"| as DataTabe;returnmydatatabe;
}

}
}
I make a smpe check, f the data s aready n the cache I take t from there. If not, I get t
from the datasource.Run your appcaton and you w see the resuts n the grd. Refresh
the page and the records w be served from the cache.
11) Every tme we add somethng nto the cache we can specfy severa attrbutes regardng
the chach entry. We can specfy attrbutes ke Expires#we specfy when the cache w be
fushed. We aso can congfure the Priorit/0Dependenc/ (The dependency, ths cache
entry has on a fe or another cache entry) of the cache entry.
12) We can rewrte the code above to use the attrbutes.
Repace ths ne of code, n the )etCusto'ers-. method.
HttpContext.Current.Cache|"customers"| = mydatatabe;
wth ths ne of code
HttpContext.Current.Cache.Insert("customers",
mydatatabe, nu,DateTme.Now.AddHours(6), Cache.NoSdngExpraton);
I use the +nsert method of the Cache ob|ect.
If you want to fnd out more about/understand better what I do here have a ook here.
The parameters I pass are a key to reference the ob|ect,then the ob|ect to be added to the
cache,then I specfy I have no dependences,the expraton date s 6 hours from now and
fnay I specfy that the ob|ect n the cache w not be removed regardng the tme t was
ast accessed.
Run your appcaton and you w see the resuts n the grd. Refresh the page and the
records w be served from the cache.
13) Now et's see how to remove ob|ects from the cache. We can ca
the 1e'ovemethod.We can have mpcty removed data from the cache for reasons ke
data expraton and memory consumpton.
Let's add another method n our DataAccess cass fe.
pubc statc vod RemoveFromCache()
{
HttpContext.Current.Cache.Remove("customers");
}
Add a button to the web form. Insde the 2utton,!Clic3 even thandng routne type,
protected vod Button1_Cck(ob|ect sender, EventArgs e)
{
DataAcess.RemoveFromCache();
}

Do not forget to add the namespace n the begnnng of the fe, n my case s
using Caching;
Run your appcaton. The data w be nserted n the cache and the second request w be
served from the cache. Now cck the button. The tems w be removed from the cache.
14) Add a new tem to your ste, a web form. Leave the defaut name.Connect to your
Northwnd database. From the Server Explorer wndow( Database Exporer ) drag and drop
the customers tabe on the form. A )ridview and a s4ldatasource contro w be added to
the form. You can specfy cachng n the decaratve datasources.
I enabed cachng n the sqdatasource contro by setttng
the Ena%ledCaching to true andCacheDuration to 5677 seconds.
Run your appcaton and you w see the customers records beng served from the database
n the nta request. After that they are cached and cache serves the comng requests.
15) Whe desgnng our appcaton, we must be very carefu about cachng. Sometmes the
user must see the atest data, n some cases cachng makes no sense at a.Sometmes an
tem can reman n the cache whe a certan other condton s vad.We want to have the
data cached for performance reasons but at the same tme we want them to have the atest
data(most recent updated data) when somethng changes n the underyng data store. So
we must have some sort of depedency between the underyng data store and the cache.
There s somethng that s caed Cache Dependenc/ that brngs together cache and the
orgnna data source.
Add another tem on your webste, a web form.Leave the defaut name.Add
a )rid"iewcontro and an O%*ectDataSource contro on the form.Add another tem n your
webste, an xm fe. Ths s gong to be an xm fe about footbaers.The contents of the xm
fe are,
<?xm verson="1.0" ?>

<footbaers>
<footbaer Poston="Attackng Mdfeder">
<team>Lverpoo</team>
<name>Steven Gerrard</name>
<manager>Kenny Dagsh</manager>
<prce>40.000.000</prce>
</footbaer>
<footbaer Poston="Strker">
<team>Manchester Unted</team>
<name>Wayne Rooney</name>
<manager>Aex Ferguson</manager>
<prce>60.000.000</prce>
</footbaer>
<footbaer Poston="Strker">
<team>Barceona</team>
<name>Lone Mess</name>
<manager>Pep Guardoa</manager>
<prce>110.000.000</prce>
</footbaer>
<footbaer Poston="Centra Defender">
<team>Chesea</team>
<name>|ohn Terry</name>
<manager>Caros Ancheott</manager>
<prce>30.000.000</prce>
</footbaer>
<footbaer Poston="Strker">
<team>Manchester Cty</team>
<name>Caros Tevez</name>
<manager>Roberto Manchn</manager>
<prce>65.000.000</prce>
</footbaer>
<footbaer Poston="Stker">
<team>Panathnakos</team>
<name>Cbr Csse</name>
<manager>Zesuado Ferrera</manager>
<prce>15.000.000</prce>
</footbaer>
</footbaers>
16) We want to get the records dspayed n the )rid"iew contro through
theO%*ectDataSource contro and the ntermedate data access ayer.
We must wrte a statc method n the data access ayer cass fe to get the footbaers data
back from the xm fe.We must wrte the code n a way that the data s cached unt changes
take pace n the underyng xm fe.
pubc statc DataTabe GetFootbaers()
{
DataTabe myxmtabe = nu;f (HttpContext.Current.Cache|"footbaers"| ==nu)
{
strng xmfename = HttpContext.Current.Server.MapPath("Footbaers.xm");
DataSet ds = new DataSet();
ds.ReadXm(xmfename);
myxmtabe = ds.Tabes|0|;
CacheDependency dependency
= newCacheDependency(xmfename);HttpContext.Current.Cache.Insert("footbaers",
myxmtabe, dependency);
}
ese
myxmtabe = HttpContext.Current.Cache|"footbaers"| as DataTabe;returnmyxmtabe;

}
The code s more or ess smar wth the one we wrote prevousy.We check f the data s n
the cache and f not I read the fe name, I create a dataset,f t wth data from the xm fe
and I return the datatabe.THe most mportant bt of the method are these 2 nes.
CacheDependency dependency = new CacheDependency(xmfename);
HttpContext.Current.Cache.Insert("footbaers", myxmtabe, dependency);
I create a dependency ob|ect by passng as a parameter the xm fename. I nsert then n
the cache the key, the datatabe and the dependency.
Set the Ob|ectDataSource Select8ethod attrbute to the method )et(oot%allers and
the9/peNa'e to the Caching.DataAccess.The markup foows beow
<asp:Ob|ectDataSource ID="Ob|ectDataSource1" runat="server"
SeectMethod="GetFootbaers" TypeName="Cachng.DataAcess"></asp:Ob|ectDataSource
>
Then set the DataSource+D property of the )rid"iew contro to
the O%*ectDataSource,contro.Run your appcaton.You w see the xm data beng
dspayed on the screen.
Refresh the browser wndow. XML data s beng served from the cache.Leave the browser
wndow open. Change somethng n the xm fe and then refresh the page.The browser
wndow w refect the new changes. In that case the dependency rue comes nto pace. The
data s cached s fushed from the cache and retreved from the xm fe as ntended.
17) Add a new tem on the form, a web form. Name t SQLDependenc/cache.aspx.We w
demonstrate n ths exampe how to use sq dependency cache wth sq server
databases.Add a )rid"iew contro and an O%*ectDataSource contro on the form.
We w need to add another statc method n our data access ayer.We w get data from
theCategories tabe of the Northwnd database.THe code ooks ke ths
pubc statc DataTabe GetCategores()
{
DataTabe thedatatabe = nu;f (HttpContext.Current.Cache|"categores"| ==nu)
{
strng conn =ConfguratonManager.ConnectonStrngs|"NorthwndConnectonStrng"|.
ConnectonStrng;
usng (SqConnecton connecton = new SqConnecton(conn))
{
connecton.Open();
SqCommand cmd = new SqCommand("seect CategoryName,Descrpton from
dbo.Categores", connecton);
SqDataAdapter dapt = new SqDataAdapter(cmd);
SqCacheDependency dependency = new SqCacheDependency(cmd);thedatatabe
=new DataTabe();
dapt.F(thedatatabe);
HttpContext.Current.Cache.Insert("categores", thedatatabe,
dependency,DateTme.Now.AddHours(6), Cache.NoSdngExpraton);
}
}
ese
thedatatabe = HttpContext.Current.Cache|"categores"| as DataTabe; returnthedatatabe;
}
The code s very easy to foow. The most mportant bt s the foowng nes. We create an
SOL cache Dependency that s nked wth the specfc command ob|ect.
Then when I nsert the tem n the cache I specfy the dependency ob|ect.
SqCacheDependency dependency = new SqCacheDependency(c'd);
HttpContext.Current.Cache.Insert("categores",
thedatatabe, dependenc/,DateTme.Now.AddHours(6), Cache.NoSdngExpraton);
Set the Ob|ectDataSource Select8ethod attrbute to the methods )etCategories and
the9/peNa'e to the Caching.DataAccess.The markup foows beow
<asp:Ob|ectDataSource ID="Ob|ectDataSource1" runat="server"
SeectMethod="GetCategores" TypeName="Cachng.DataAcess"></asp:Ob|ectDataSource
>
Then set the DataSource+D property of the )rid"iew contro to the O%*ectDataSource,contro.
18) In order for ths to work we must add another tem n the webste.Add a goba appcaton cass fe, )lo%al.asax. In the Application!Start-. event we shoud type,
<%@ Import Namespace = "System.Data.SqCent" %>
.......
vod Appcaton_Start(ob|ect sender, EventArgs e)
{
// Code that runs on appcaton startup
strng conn =ConfguratonManager.ConnectonStrngs|"NorthwndConnectonStrng"|.
ConnectonStrng;
SqDependency.Start(conn);
}
Run your appcaton.You w see the data from the tabe beng dspayed on the
screen.Refresh the browser wndow and you w see that the data s beng served from the
cache.Leave the wndow open.Make some changes n theCategories tabe and refresh the
page. You w see the updated data beng refected on the screen causng the cache to fush
due to the changes n the resutset and the sq cache dependency.
Ema me f you need the code.
Hope t heps!!!

Das könnte Ihnen auch gefallen