Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Chapter 23


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Chapter 23

  1. 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. 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 retrievingdata from memory is much more efficient than retrievingthe data from other locations, such as a database or a file.When you store information in a cache the lifetime of thatinformation is at the discretion of the server. If the cachebecomes full or other applications consume a largeamount of memory, data will be selectively evicted from thecache, ensuring that the application continues to performwell.
  3. 3. A good caching strategy identifies the most frequentlyused pieces of data that are the most time-consuming tocreate and stores them. If you store too muchinformation, you risk filling up the cache with relativelyunimportant data and forcing out the content you reallywant to keep.Cache data (or web pages) that are expensive: Theresults of a database query or contents of a file.Cache data (or web pages) that are used frequently: Thelist of product categories instead of product detail pages.
  4. 4. ASP.NET really has two types of caching.Output caching: It stores a copy of the final renderedHTML page that is sent to the client. The next client thatsubmits a request for this page doesn’t actually run thepage. 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 ofinformation that are time-consuming to reconstruct (suchas a DataSet retrieved from a database) in the cache.Other pages can check for the existence of thisinformation and use it, thereby bypassing the stepsordinarily required to retrieve it.
  5. 5. With output caching, the final rendered HTML of the pageis cached. When the same page is requested again, thecontrol objects are not created, the page life cycle doesn’tstart, and none of your code executes. Instead, thecached HTML is served.You can cache an ASP.NET page in two ways.Insert the OutputCache directive at the top of your .aspxfile, 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. 6. When you request the page with additional query stringinformation, ASP.NET will examine the query string. If thestring matches a previous request and a cached copy ofthat page exists, it will be reused. Otherwise, a new copyof the page will be created and cached separately.You can set the VaryByParam attribute to * to indicate thatthe page uses the query string and to instruct ASP.NET tocache separate copies of the page for different querystring arguments:<%@ OutputCache Duration="20" VaryByParam="*" %>Or<%@ OutputCache Duration="20“VaryByParam="ProductID;CurrencyType" %>
  7. 7. ASP.NET includes a feature called cache profiles thatmakes it easy to apply the same caching settings to agroup of pages.With cache profiles, you define a group of caching settingsin the web.config file, associate a name with thesesettings, and then apply these settings to multiple pagesusing the name.That way, you have the freedom to modify all the linkedpages at once simply by changing the caching profile inthe web.config file.
  8. 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 CacheProfileattribute:<%@ OutputCache CacheProfile="ProductItemCacheProfile"VaryByParam="None" %>
  9. 9. The basic principle of data caching is that you add itemsthat are expensive to create to a built-in collection objectcalled Cache.Cache is a property of the Page class, and it returns aninstance 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. 10. Absolute expirations are best when you know theinformation in a given item can be consideredvalid only for a specific amount of time (such as a stockchart or a weather report).Sliding expiration, on the other hand, is more usefulwhen you know that a cached item will always remainvalid (such as with historical data or a product catalog)but should still be allowed to expire if it isn’t beingused.
  11. 11. You cannot set both a sliding expiration and anabsolute expiration policy at the same time. If you wantto use an absolute expiration, set the slidingExpirationparameter to TimeSpan.ZeroCache.Insert("MyItem", obj, null,DateTime.Now.AddMinutes(60), TimeSpan.Zero);To set a sliding expiration policy, set theabsoluteExpiration parameter to DateTime.MaxValueCache.Insert("MyItem", obj, null,DateTime.MaxValue, TimeSpan.FromMinutes(10));
  12. 12. private DataSet RetrieveData(){string connectionString =WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;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;}
  13. 13. 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;}
  14. 14. The SqlDataSource and ObjectDataSource support built-in data caching.Using caching with these controls is highly recommended, because theycan be more inefficient than handwritten data access code.Caching Properties of the Data Source Controls
  15. 15. As time passes, the information in your data source maychange. If your code uses caching, you may remainunaware of the changes and continue using out-of-dateinformation from the cache.To help mitigate this problem, ASP.NET supports cachedependencies. Cache dependencies allow you to make acached item dependent on another resource, so that whenthat resource changes, the cached item is removedautomatically.ASP.NET includes three types of dependencies:• Dependencies on files or folders• Dependencies on other cached items• Dependencies on a database query
  16. 16. To use a cache dependency, you need to create a CacheDependencyobject. You then need to supply the CacheDependency object whenyou add the dependent cached item.For example, the following code creates a CacheDependency thatCreate a CacheDependency that depends on an XML file namedProductList.xml. When the XML file is changed, theCacheDependency will be invalidated, and the dependent cacheditem will be evicted from the cache immediately.Dim dom As XmlDocument()dom.Load(Server.MapPath("ProductList..xml")Cache(“prodInfo") = domCacheDependency prodDependency = new CacheDependency(Server.MapPath("ProductList.xml"));Cache.Insert("ProductInfo", prodInfo, prodDependency);
  17. 17. 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);
  18. 18. 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);