This article mainly explains the built-in cache function of objectdatasource in asp.net 2.0.With simple configuration,We can cache the data obtained by calling the selectmethod method of the objectdatasource.


In terms of computer science,Caching is to place a backup of the required data or information somewhere,A process that facilitates quick access.Take a data-driven program as an example,Most of the program's time is wasted on data queries.To improve the performance of such programs,The usual practice is to store the query results in the program's memory.

Asp.net 2.0 provides a variety of caching methods.Web pages and user controls can be cached through output caching;Similarly, we can cache data at the control level through the objectdatasource and sqldatasource controls;At the same time, asp.net's data cache provides a rich cache interface (caching api) for page developers to programmatically cache objects.In this article and the next three articles, we will examine the cache properties of the objectdatasource and the data cache;We will also explore how to cache application-wide data at startup,And refresh the cached data by using sql cache dependencies.

The main cache points

Because caching improves the overall performance of the program by placing a copy of the data in a place that is easily accessible.Since it is just a copy,When the source data changes,Copies cannot be updated synchronously.To do this, the page developer should develop a standard to clear it out of memory,You can use one of the following two methods:

Time-based standard:Items added to memory can only reside in memory for a fixed or flexible period of time.For example, a developer can set a time period,For example, 60 seconds, when the entry is added to memory,No matter how often it is accessed,It will be cleared after 60 seconds;If it is flexible,When it was last visited,The time that has not been accessed again exceeds 60 seconds, it will also be cleared.

Dependency-based standard:when adding an entry to memory, assign a dependency to it, and clear the entry when the corresponding slave of the entry changesThe slave can be a file;Another cache entry;Or simply a combination of the two;of course, it can also be sql cache dependencies, which can add entries to memory,Clear entries when source data changes.We will be in the next article "Use sql cache dependency sqlcachedependencyIn detail.

Regardless of the standard,Before the entry is cleared,We can all visit it.If memory reaches its limit,It will clear the existing entries before adding new entries.Therefore, when dealing with cached data, it is important that we fully consider the possibility that the cached data has been cleared.In the next article "Cache data in a layered architecture》 We examine which mode is used to access data from memory.

Cache is a more economical way to improve program performance.As Steven smith explained in his article "asp.net caching:techniques and best practices:":"Caching is a great way to get" best "performance,Does not require much time and analysis.… Storage is also cheap,To get the performance you expect,You need 30 seconds to rely on caching technology;it can take days or weeks to optimize your code and database ... "

While caching can significantly improve system performance,But not for all applications,For example, some real-time programs that frequently update data are not suitable.

But for most programs,Still applicable.For more background information on caching in asp.net 2.0, please refer to the caching for performance section of the asp.net 2.0 quickstart tutorials series.

Step 1:Create a cache page

Before we start,First let's take some time to add the pages needed for the last four tutorials including this one.We first create a new folder called cache in the project.Next, add the following pages to the catalog,And configured to use the site.master master page.






Figure 1:Creating relevant asp.net pages

Like other folders,The default.aspx page in the caching folder displays the articles in this series.Remember that the user control sectionleveltutoriallisting.ascx provides this functionality,Drag it onto the page in design mode.

Figure 2:Adding the user control sectionleveltutoriallisting.ascx to the default.aspx page

Finally, add these pages to the web.sitemap file, in particular, after "working with binary data"<sitemapnode&:::

<sitemapnode url="~/caching/default.aspx"
 description="learn how to use the caching features of asp.net 2.0.">
 <sitemapnode url="~/caching/objectdatasource.aspx"
 description="explore how to cache data directly from the
 objectdatasource control. "/>
 <sitemapnode url="~/caching/fromthearchitecture.aspx"
 description="see how to cache data from within the
 architecture. "/>
 <sitemapnode url="~/caching/atapplicationstartup.aspx"
 description="learn how to cache expensive or infrequently-changing
 queries at the start of the application. "/>
 <sitemapnode url="~/caching/sqlcachedependencies.aspx"
 description="examine how to have data automatically expire from the
 cache when its underlying database data is modified. "/>

Figure 3:The site map contains articles from the cache chapter

Step 2:Display the product in a web page

This article examines how to use the built-in cache function of the objectdatasource control.Before you start,We first need to create a page,Use an objectdatasource control to call the productsbll class to obtain product information.Then display it with the gridview control.

First open the objectdatasource.aspx page in the cache folder. Drag a gridview control from the toolbox to the page,Set its id to products, and then choose to bind it to an objectdatasource control from the smart tag with id as productsdatasource. Let this objectdatasource use the productsbll class.

Figure 4:Setting up the objectdatasource control to use the productsbll class

On this page,We want to create a gridview control that allows editing. When the cached data in the objectdatasource control changes,We can see what exactly happens through the gridview interface.Select the default getproducts () method in the select tag, but select the updateproduct () overload method that accepts productname, unitprice, and productid as input parameters in the update tag.

Figure 5:Selecting the overloaded updateproduct () method in the update tab

Finally, select "(none)" in the insert and delete tags, and click the Finish button.Once the "Set Data Source Wizard" is completed, visual studio will set the oldvaluesparameterformatstring property of the objectdatasource control to original_ {0}. Just like in Chapter 16 of the previous tutorial,Overview of inserting, updating, and deleting dataThe same thing is discussed in "This attribute is either deleted,Either set it to {0}, otherwise the update operation will report an error.

In addition, after completing the wizard,Visual Studio will add all data columns of the product to the gridview control and delete all boundfields except productname, categoryname and unitprice. Then, change the headertext attributes of the above 3 columns to product "," category "and" price ". Since productname is required,Transform the productname column into a template column and add a requiredfieldvalidator control to edititemtemplate. Similarly, convert the unitprice column into a template column.And add a comparevalidator control to ensure that the user entered a valid currency value greater than or equal to 0.In addition,You can also make some interface improvements,For example, center the unitprice value, or do some formatting for the read-only and edit interface of unitprice respectively.

point Click related items in gridview's smart tab to start editing, paging, and sorting functions.

Note:Want to review how to customize the gridview editing interface?Please refer to the previous article 20 "Custom data modification interface》

Figure 6:Enable gridview's editing, sorting, and paging functions.

After modifying the gridview,The gridview and objectdatasource code declarations look like this:

<asp:gridview runat="server" autogeneratecolumns="false"
 datakeynames="productid" datasourceid="productsdatasource"
 allowpaging="true" allowsorting="true">
 <asp:commandfield showeditbutton="true" />
 <asp:templatefield headertext="product" sortexpression="productname">
 <asp:textbox runat="server"
 text="<%#bind (" productname ")%>"></asp:textbox>
 controltovalidate="productname" setfocusonerror="true"
 errormessage="you must provide a name for the product."
 <asp:label runat="server"
 text="&%;bind (" productname ")%>"</asp:label>
 <asp:boundfield datafield="categoryname" headertext="category"
 readonly="true" sortexpression="categoryname" />
 <asp:templatefield headertext="price" sortexpression="unitprice">
 $<asp:textbox runat="server" columns="8"
 text="<%#bind (" unitprice "," {0:n2} ")%>"></asp:textbox>
 controltovalidate="unitprice" display="dynamic"
 errormessage="you must enter a valid currency value with no
 currency symbols. also, the value must be greater than
 or equal to zero. "
 operator="greaterthanequal" setfocusonerror="true"
 type="currency" runat="server"
 <itemstyle horizontalalign="right" />
 <asp:label runat="server"
 text="<%#bind (" unitprice "," {0:c} ")%>" />
<asp:objectdatasource runat="server"
 oldvaluesparameterformatstring="{0}" selectmethod="getproducts"
 typename="productsbll" updatemethod="updateproduct">
 <asp:parameter name="productname" type="string" />
 <asp:parameter name="unitprice" type="decimal" />
 <asp:parameter name="productid" type="int32" />

As shown in Figure 7, gridview lists the name, category, and price information for each product. Take a few minutes to test the page-sort the results,View the tabs,Edit a record.

Figure 7:Name, category and price information for each record

Step 3:Examine how objectdatasource requests data

The gridview with id products retrieves the data by calling the select () method of the objectdatasource named productsdatasource and displays it.The objectdatasource creates an instance of the productsbll class of the business logic layer and calls its getproducts () method, which in turn calls the getproducts () method of the products access adapter of the data access layer. The data access layer connects to the database northwind and executes the selected select query. The query data is returned to the data access layer in the form of northwinddatatable.The datatable object is passed back to the business logic layer in turn.objectdatasource, gridview controls. The gridview control creates a gridviewrow object for each datarow in the datatable. Each gridviewrow object is finally compiled into html and returned to the client.Presented in the visitor's browser.

Any time,When the gridview control needs to be bound,Execute in the sequence of events described above.For example, the first login page;Passing data from one page to another;Sort in gridview;change data through the built-in edit or delete interface of gridview.When the gridview's view (view sta is set to disabled), the gridview will be re-bound each time the page is passed back;Of course, we can explicitly call the databind () method to bind the gridview.

In order to more clearly reveal the frequency of data retrieval from the database,We show a message,Prompt the program to retrieve data at some point.To do this, add a label control with an id eventsEvents to the gridview control, clear its text property, and set its enableviewstate property to false. Add a button control below the label control and set its text property to "postback".

Figure 8:Adding label and button controls to the gridview

Throughout the data retrieval process,First, the selection event of the objectdatasource is triggered, and its corresponding set method is called.Create an event handler for the event,Add the following code:

protected void productsdatasource_selecting (object sender, objectdatasourceselectingeventargs e)
 odsevents.text="-selecting event fired";

Every time objectdatasource starts to retrieve data,The label control will display the text "selecting event fired".

access Visit this page in your browser.When logging in for the first time,The text "selecting event fired" is displayed.When clicking the "postback" button, we noticed that the text disappeared (provided you set the enableviewstate property of the gridview to the default value of true). This is because when the page is passed back,Gridview loads data for reconstruction through its view state, so it is no longer necessary to retrieve the database through objectdatasource to get data for reconstruction.However, sorting, pagination, editing, etc. will cause gridview to rebind to the data source,So the text "selecting event fired" appears again.

Figure 9:When the gridview is re-bound to the data source,Display text "selecting event fired"

Figure 10:Clicking the "postback" button causes the gridview to get data from the view state

need You need to retrieve data from the database every time you paginate and sort,This looks like a waste of resources.Even if gridview does not support sorting and pagination,Everyone needs to retrieve data from the database every time they log in to the page for the first time (if the view state is set to disabled, the data will also be retrieved every time the page turns). If the gridview displays the same data for all users,Then extra database queries are wasteful.We can cache the data returned by the getproducts () method,Then bind the gridview to these cached data.

Step 4:Cache data with objectdatasource

Just simply set some properties,We can let the objectdatasource automatically cache its retrieved data.The following summarizes the cache-related properties of the objectdatasource control:

enablecaching—must be set to true, default is false.

cacheduration—cache time,In seconds.The default is 0. The objectdatasource control caches data only when the enablecaching property is set to true and the cacheduration is set to a value greater than 0.

cacheexpirationpolicy—Can be set to absolute or sliding. If absolute, when it is set in seconds,how many seconds the objectdatasource will cache the retrieved data;If it is sliding, when it is set to how many seconds,Once the cached data is not accessed for so many seconds,The cache is terminated.The default is absolute.

cachekeydependency—Use this attribute to associate the cache entry of the objectdatasource with an existing cache slave.Use it to clear cache entries from memory in advance.In most cases, this attribute is used to associate the sql cache dependency with the cache of the objectdatasource.We will discuss this topic in a later tutorial "Use sql cache dependency sqlcachedependencyInvestigate.

Let's set the data cache time of objectdatasource with idsdatasource to 30 seconds. Set its enablecaching property to true;set its cacheduration property to 30;cacheexpirationpolicy property to the default absolute.

Figure 11:Setting the cache time of objectdatasource to 30 seconds

Save your settings,And view in the browser.When you first log in to the page,The text "selecting event fired" will be displayed,Because the original data has not been cached.But you click the "postback" button, or pagination,When sorting, or clicking the edit or cancel button,The text "selecting event fired" will not be displayed.The reason is that the selecting event will be triggered only when the objectdatasource control retrieves the data;if the objectdatasource control gets data from the cache, the selecting event will not be triggered.

After 30 seconds, the data will be cleared from memory;Or call the insert, update, or delete methods of the objectdatasource control and the data will be cleared.So after 30 seconds or click the "update" button, edit, cancel button,Or sorting and pagination will cause the objectdatasource to retrieve the data,When the selecting event is triggered, the text "selecting event fired" will be displayed again.Finally, the retrieved data is cached.

Note:If you see the text "selecting event fired" appear frequently,It is likely that the memory capacity is too small.If there is not enough capacity,The data added by objectdatasource to memory may be cleared.If objectdatasource does not or only occasionally cache data,Please close some applications to free up memory,Then try again.

Figure 12 reveals the caching process of objectdatasource.When the text "selecting event fired" appears on the screen,That's because the data was not found in the cache,Related searches must be performed.When the text disappears,That's because the data is cached.When the required data is obtained from the cache,No data query is performed.

Figure 12:objectdatasource stores and retrieves data in the data cache

Every asp.net application has its own data cache instance,All pages and users are accessible.That means for the data cached by the objectdatasource control,Anyone logged in to this page can access it.To verifyOpen the objectdatasource.aspx page in a browser. When you log in to the page for the first time,The text "selecting event fired" appears (assuming that the cached data from the previous test has been cleared by this time). Open a second browser,Copy and paste the url address in the first browser.In the second browser,The text "selecting event fired" is not displayed,Because it uses data cached by the first browser page.

When adding retrieved data to memory,The objectdatasource uses a value called cache key, which includes:cacheduration and cacheexpirationpolicy attribute values;The type of the business object called by objectdatasource, which is specified by the typename attribute (for example:productsbll);the value of the selectmethod attribute,And the names and values ​​of the parameters in the selectparameters parameter set;the values ​​of the startrowindex and maximumrows properties,It is used to perform custom paging.

The combination of these attribute values ​​to form the cache key value is to provide a unique identification value for each cache entry.For example, in the previous tutorial,We use the getproductsbycategoryid (categoryid) method of the productsbll class to get all products of a specified category.If a user views the product information of a beverage category (with a categoryid value of 1) on the page,If the objectdatasource control ignores the value of selectparameters during data caching, when another user logs in to the page to view product information of the condiment categoryIt happens that the beverage product information is cached in memory,The second user will see product information for the beverage category,Not the product information of the condiment he wants.Therefore, when the cache key value includes the value of electparameters,When objectdatasource caches data, it can distinguish between condiments and beverages.

Data update out of sync (stale data) problem

When one of the insert, update and delete methods of the objectdatasource control is called,It will clear cache entries from memory.The advantage of this is that when the data is modified from the page, the cached old data is cleared.However, the objectdatasource may still "unupdate the data" (that is, the source data has changed,And the cached data is not updated synchronously).The simplest example is to modify the data directly from the database,For example, a database administrator runs a script,Modify some records in the database.

Here we explore a delicate situation.Although it will clear the cache data when calling the data modification method of objectdatasource,But those cache entries (such as cacheduration, typename, selectmethod, etc.) that match the "combination of property" of the objectdatasource are cleared. If you have 2 objectdatasources controls, they update the same data,When using different selectmethods or selectparameters, when the first objectdatasources control updates a row of records and clears the cache data corresponding to that rowThe second objectdatasources control still uses the cached data corresponding to that row.Let ’s do a verification.Create a page,Contains an editable gridview control whose corresponding objectdatasource control is set to use the cache,And call the getproducts () method of the productsbll class to get the data.Add gridview and objectdatasource controls on this page (or create another page), but set the second objectdatasource control to call the getproductsbycategoryid (categoryid) method. Because the selectmethod property of the two objectdatasource controls is different,Therefore, they each have different cache values.If you edit a product in the first gridview control,Then rebind the data in the second gridview control (such as paging, sorting, etc.), we see that the value of the product in the second gridview control is still "old cached data" (not the first gridview (Modified value of the control)

in short,If you are willing to use "old cached data", then only time-based expiries (that is, setting specific cache time lengths) are used. If the data is required to be updated in a timely manner,Set the cache time short.If "old cached data" is not allowed, either discard the cache,Either use sql cache dependencies (you can think of it as database data you cache). We will explore sql cache dependencies later.

to sum up:

In this article we examined the built-in caching capabilities of objectdatasource.Just set few attributes,We can cache the data obtained by calling the selectmethod method of the objectdatasource.The cacheduration and cacheexpirationpolicy attributes specify the time and type of cache (absolute or sliding). The cachekeydependency attribute associates the cache entity of the objectdatasource with the existing cache dependency.Generally it is sql cache dependencies.

Because objectdatasource simply caches data,We can programmatically implement this kind of functionality built into objectdatasource.But it doesn't make sense to do this at the presentation level,Because the objectdatasource control provides this function.However, we can implement caching at other levels of the architecture.For this we need a logic,It's the same as the objectdatasource call.In the next article we will look at how to programmatically handle data caching within the architecture.

Happy programming!

About the Author

  • Previous AngularJS ng-blur instruction detailed and simple examples
  • Next jquery implementation interface no refresh loading login registration