Data Caching

for RuBoard

Data caching is another feature provided by ASP.NET that can significantly increase the speed of your data access code, by not retrieving the same data repetitively. In ASP.NET, the cache is implemented using the Cache object. Because it works just like any dictionary object, it's easy to use. The following line of code will store a DataSet in the Cache object with the name "Categories":

 Cache("Categories") = dsCategories 

It can be read out of the cache later with the following code:

 myDataSet = Ctype(Cache("Categories"), DataSet) 

To implement data caching in your Web application, first check to see if the DataSet is stored in the cache. If it is, use the cached version. Otherwise , load the DataSet data from the database and then store the DataSet in the cache for the next call. Listing 23.3 demonstrates how to store a DataSet in the cache.

Listing 23.3 Using the ASP.NET Cache Object
 public sub GetCategoryData()   'if the dataset exists in the cache   if Page.Cache("Categories") <> "" then      'Return the cached DataSet      return Ctype(Page.Cache("Categories"), DataSet)   'otherwise, retrieve DataSet from database   else      'Create ADO.NET connection and command objects      SqlConnection conn = new SqlConnection( _          ConfigurationSettings.AppSettings("ConnectionString"))      SqlCommand cmd = new SqlCommand("SELECT * " + _                                           "FROM Categories", conn)      'Create DataAdapter and DataSet objects      Dim myAdapter as SqlDataAdapter = new SqlDataAdapter(cmd)      Dim ds as DataSet = new DataSet()      'Open connection to database      conn.Open()      'Fill the DataSet      myAdapter.Fill(ds, "Categories")      'Close connection to database      conn.Close()      'Place the dataset in the cache      context.Cache("AllDomains") = ds      'Return the dataset      Return ds end sub 
for RuBoard


Sams Teach Yourself ADO. NET in 24 Hours
Sams Teach Yourself ADO.NET in 24 Hours
ISBN: 0672323834
EAN: 2147483647
Year: 2002
Pages: 237

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net