Manipulating data in ASP.net 2.0 58: Caching Data During program startup phase self-study process

Source: Internet
Author: User
Tags httpcontext

Introduction:
The previous 2 chapters examine the caching of data at the presentation layer and cache layer. In the 56th chapter, we discuss the cache properties of ObjectDataSource set in the presentation layer to buffer the data. In the 57th chapter, we explored the creation of a separate cache layer. These 2 chapters use the "Stress load" (reactive loading) pattern to cache data. In this mode, each time the data is requested, the system checks to see if it is in memory, and if not, gets the data from the data source-such as the database-and then stores it in memory. The advantage of this pattern is that it is easy to execute, and one of the drawbacks is that it should be performed on a "request" (requests). Imagine, in the previous chapter, we use the cache layer to display product information, when the first time you log on to the page, or cached data because of the end of the cache time, and so on, after the memory is purged, when the page again, because the data is not stored in memory, requests can only get data from This can take longer than getting data directly from memory.

"Preloaded" (proactive loading) can be preloaded with 2 different modes of loading data. The first model, proactive loading, uses methods (process) to determine whether the source data (underlying data) has changed, and to update the cached data in a timely manner-for example, periodically checking the source data, or when the source data changes, Notify the update immediately. However, the disadvantage of this model is that it is difficult to execute, you must create, manage, execute a specific method to check the source data changes to update the cached data.

Another pattern, also discussed in this article, is to load data into memory when the program starts. This pattern is especially useful for caching static data, such as locating records in a database table.
Note: For the difference between "stress load" (reactive loading) and "preloaded" (proactive loading), refer to the article Caching architecture Guide for. NET Framework Applications "Managing the Contents of a Cache" chapter: (http://msdn2.microsoft.com/en-us/library/ms978503.aspx)

Step one: Decide which data to cache during the program startup phase

The example of the reactive loading pattern we explored in the previous 2 chapters is appropriate for processing this data: periodically changing and generating (generate) data does not take too long. However, if the cached data has never changed, then the cycle (expiry) used by the reactive loading pattern is somewhat superfluous. In addition, if the data that needs to be cached takes a long time to produce, the user will wait a long time to retrieve and return the data when the user requests that the memory is empty. In this regard, you can consider that static data and data that takes a long time to generate will be cached during the program startup phase.

Although the database has a lot of dynamic, often changed values, but also a lot of static values. For example, the database table patients has a primarylanguage column whose value can be Chinese, Spanish, French, Russian, Japanese, and so on. However, we do not store "Chinese" or "French" strings directly in the table patients, but are stored in the lookup table languages. Figure 1:john Doe's primary language is Chinese, and Ed Johnson's is Russian.


Figure 1: Table languages the lookup table used by table patients

In the user interface for editing or creating a new patient, you will include a Drop-down list box that lists all the language items in the table languages. Do not cache, each login to the interface, the system will query the table languages, so obviously and waste is not necessary. Because the table languages does not change frequently.

We can cache the data languages using the reactive loading pattern discussed above. However, the reactive loading mode uses a time based cache cycle (time-based expiry), which is not necessary for static data. The best way to do this is to preload during the startup phase of the program.

In this article, we'll explore how to cache lookup tables (lookup table, for example, languages tables for patients tables) data and other static information.

Step two: Explore different ways of caching data

In a asp.net application, we can use a variety of methods to cache information. In the previous tutorial we saw the data cache, but we can also cache objects (objects) by using the static members (static member) or application state (application states).

When dealing with a class, we should instantiate it before accessing its members. For example, to invoke a method in the BLL layer, we first create an instance of the class:

PRODUCTSBLL Productsapi = new Productsbll ();
Productsapi.somemethod ();
Productsapi.someproperty = "Hello, world!";

Before invoking SomeMethod or processing Someproperty, we must first create an instance of a class with the keyword new. SomeMethod and Someproperty to correspond to a specific instance, the life cycle (lifetime) of these members depends on the life cycle of the corresponding object. On the other hand, Static members, such as variables, properties, methods, and so on, are shared for all instances of the class, so their lifecycle is as long as the class's lifecycle. The static members are identified with the keyword static.

In addition to the static members, you can also use application state. Each asp.net application contains a name/value set that is shared by all pages and users of the application. You can access it by HttpContext the class class's Application Property attribute. In the background code of the page we can access it like this:

application["key"] = value;
Object value = application["Key"];

The data cache provides a wealth of caching APIs (application interfaces), a mechanism based on time and dependent cache cycles (Time-and dependency-based expiries), and cache item priorities. In this article, we'll see 3 techniques for caching static data.

Step three: Cache the Suppliers table data

The Northwind database we use does not have a lookup table, and the values of the 4 tables used by the DAL layer are not static. It is not necessary to take the time to add a new database table to the DAL layer, add new classes and new methods to the BLL layer, and we assume in this tutorial that the table suppliers data is static, so we start the program by caching its data.

First, we create a new class named StaticCache.cs in the CL folder.


Figure 2: Creating the StaticCache.cs class in the CL folder

We need to add a way to load the data at the start of the program, as well as a way to return data from memory.

[System.ComponentModel.DataObject]
public class Staticcache
{
 private static northwind.suppliersdatatable suppliers = NULL;

 public static void Loadstaticcache ()
 {
 //Get Suppliers-cache using a static member variable
 SUPPLIERSBLL su PPLIERSBLL = new Suppliersbll ();
 Suppliers = Suppliersbll.getsuppliers ();
 }
 [Dataobjectmethodattribute (Dataobjectmethodtype.select, true)]
 public static northwind.suppliersdatatable Getsuppliers ()
 {return
 suppliers;
 }
}

In the above code, we use a static member variable suppliers in the Loadstaticcache () method to hold the result returned by the Getsuppliers () method of the Suppliersbll class. The Loadstaticcache () method should be invoked at the program startup stage. Once the data is loaded into memory at startup, any page that uses supplier information can call the Getsuppliers () method of the Staticcache class. As a result, access to the database to obtain suppliers information occurs only once, in the start-up phase.

In addition to the static member variables, we can also use the application state or the data cache. The following code modifies the class by using the application state:

[System.ComponentModel.DataObject]
public class Staticcache
{public
 static void Loadstaticcache ()
 {
 //get Suppliers-cache using Applicat Ion State
 SUPPLIERSBLL SUPPLIERSBLL = new Suppliersbll ();
 httpcontext.current.application["Key" = Suppliersbll.getsuppliers ();
 }

 [Dataobjectmethodattribute (Dataobjectmethodtype.select, true)]
 public static northwind.suppliersdatatable Getsuppliers ()
 {return
 httpcontext.current.application["key" ] as northwind.suppliersdatatable;
 }


In the Loadstaticcache () method, the supplier information is stored in the application variable key. In the Getsuppliers () method, it is returned as a northwind.suppliersdatatable type. Since we can use application["key" in the background code of the ASP.net page to access application state, we must use the httpcontext.current.application["key "] to get the current HttpContext.

Again, we can use the data cache as follows:

 [System.ComponentModel.DataObject] public class Staticcache {public static void Load
 Staticcache () {//Get Suppliers-cache using the data cache suppliersbll SUPPLIERSBLL = new SUPPLIERSBLL ();  HttpRuntime.Cache.Insert (/* Key/"key",/* value */suppliers,/* dependencies/NULL,/* absoluteexpiration * * cache.noabsoluteexpiration,/* slidingexpiration/cache.noslidingexpiration,/* Priority * * CACHEITEMPRIORITY.N
 Otremovable,/* onremovecallback * * null); [Dataobjectmethodattribute (Dataobjectmethodtype.select, true)] public static northwind.suppliersdatatable
 Getsuppliers () {return httpruntime.cache["key"] as northwind.suppliersdatatable; }
}

Add an entry to data Cache without specifying a time period (no time-based expiry) to this end, we System.Web.Caching.Cache.NoAbsoluteExpiration and System.Web.Caching.Cache.NoSlidingExpiration value as one of the input parameters. In the Insert () method of the data cache above, we specify the priority of the cache entry (priority). The priority is used to indicate which entries should be removed from memory when the memory capacity is low. Here, we set the priority to not be removable (that is, the corresponding null), which ensures that it is not removed when there is not enough memory.

  Note: This article downloads the Staticcache class class in the code using the static member variable technique, and the code for application state and data cache technology can be found in the annotation section of the class file.

Step Fourth: Executing code in program startup

In order to execute code when the program starts, we need to create a file named Global.asax. This file contains event handlers for application, session, and request-level events. In this file we will add code to execute when the program starts.

To add a Global.asax file to the site root, in Visual Studio Solution Explorer, right-click the Web site project, select Add New Item, choose the Global Application project type from the Add New Item dialog box, and then click the Add button.

  Note: If the Global.asax file already exists in your root directory, the global Application project type will not appear in the Add New Item dialog box.


Figure 3: Add the Global.asax file in the root directory.

The default Global.asax file includes 5 methods, each with a server-side (server-side) <script> tag:

application_start– when the program is started

application_end– when the program is completed

application_error– occurs whenever an unhandled (unhandled) exception occurs on a program.

session_start– executes when a session is created

session_end– occurs when the session ends or is removed

The Application_Start event handler occurs only once in the lifecycle of the program (life cycle). The program starts with a asp.net resource (Resource) that is first requested and continues to run until the program restarts. For more details on the lifecycle of the program, see the article "ASP.net Application Life Cycle Overview" http://msdn2.microsoft.com/en-us/library/ms178473.aspx

In this article, we just need to add code for the Application_Start method, and feel free to boldly remove the other methods. In Application_Start, only the Loadstaticcache () method of the Staticcacheclass class is invoked. This will load and cache the supplier information:

<%@ application Language= "C #"%>
<script runat= "server" >
 void Application_Start (object sender, EventArgs e)
 {
 staticcache.loadstaticcache ();
 }
</script>

That's all you have to do! At the beginning of the program, the Loadstaticcache () method obtains supplier information from the BLL and stores it in a static member variable (or some other cache store you use in the Staticcache class Class). For verification purposes, set breakpoints (breakpoint) in the Application_Start method and execute the program. In addition, Application_Start methods are not executed when concurrent requests (subsequent requests).


Figure 4: Verifying the execution of the Application_Start event handler with breakpoint

  Note: If you do not encounter Application_Start breakpoint during the first debugging, it is because your program has been started. You can modify the Global.asax or Web.config file to force the program to restart. You simply add (or delete) a blank line at the end of these files to quickly restart the program.

Fifth step: Displaying cached data

The Staticcache class classes now cache the supplier-related data when the program starts. To use this data at the presentation layer, we can invoke the Getsuppliers () method of the Staticcache class class by ObjectDataSource control or programmatically in the background code of the ASP.net page. Let's look at how to use the ObjectDataSource and GridView controls to show cached supplier information.

First, open the Atapplicationstartup.aspx page in the folder, drag a GridView control from the toolbox to the page in design mode, and set its ID to suppliers. Then, choose to create a new ObjectDataSource from its smart tag, named Supplierscacheddatasource, to set it to use the Getsuppliers () method of the Staticcache class class.


Figure 5: Setting the ObjectDataSource control with the Staticcache class class


Figure 6: Using the Getsuppliers () method to get the cached supplier data

When the settings are complete, Visual studio automatically adds a boundfields for each column in the suppliersdatatable. Therefore, your declaration flags for the GridView and ObjectDataSource controls should look something like the following:

<asp:gridview id= "Suppliers" runat= "Server" autogeneratecolumns= "False" datakeynames= "SupplierID" datasourceid= " Supplierscacheddatasource "enableviewstate=" False "> <Columns> <asp:boundfield datafield=" SupplierID " headertext= "SupplierID" insertvisible= "False" readonly= "True" sortexpression= "SupplierID"/> <asp:boundfield D Atafield= "CompanyName" headertext= "CompanyName" sortexpression= "CompanyName"/> <asp:boundfield "datafield=" Address "headertext=" address "sortexpression=" Address "/> <asp:boundfield datafield=" City "headertext=" City "so
 rtexpression= "City"/> <asp:boundfield datafield= "Country" headertext= "Country" sortexpression= "Country"/> <asp:boundfield datafield= "Phone" headertext= "phone" sortexpression= "phone"/> </Columns> </asp: gridview> <asp:objectdatasource id= "Supplierscacheddatasource" runat= "Server" oldvaluesparameterformatstring = "Original_{0}" selectmethod= "Getsuppliers" Typename= "StAticcache "/>

 

Figure 7 shows the screen login to the page in the browser. The same is used to get the data using the Suppliersbll class class of the BLL layer, but instead we use the Staticcache class class to cache and return the data at the beginning of the program. You can set breakpoints in the Getsuppliers () method for Staticcache class classes to validate them.


Figure 7: Displaying cached supplier data in the GridView control

Conclusion:

Almost every data model contains static data, and the corresponding lookup table (lookup tables) is usually used. Because this information is static, it is not necessary to access the database every time the data is presented. In addition, because of its "static" nature, there is no need to set cycles (expiry) when caching data. In this article, we see how data cache, application state, and static member variables can be cached. This data is cached at the start of the program and is kept in memory throughout the program's lifecycle (Lifetime).

In this article and in the previous 2 chapters, we explored the caching of data during the lifecycle of a program and the use of a time based cache cycle (time-based expiries). When the database data is cached, we should remove the corresponding cache entry if the source data (underlying database data) is changed. In dealing with this problem, although the method of using the time based caching cycle is not perfect, it is a good solution compared to "refreshing" data programmatically. The best solution might be to use SQL cache dependencies, which we will continue to explore in the next article.

I wish you a happy programming!

Author Introduction

The author of this series of tutorials, Scott Mitchell, has six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. You can click to see all Tutorials "[translation]scott Mitchell asp.net 2.0 data tutorial," I hope to learn asp.net help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.