Manipulating data in ASP.net 2.0 56: Using ObjectDataSource Cached Data _ self-study process

Source: Internet
Author: User

Introduction

In the case of computer science, caching is the process of placing a backup of the required data or information somewhere to facilitate quick access. In the case of data processing (data-driven) programs, most of the time of the program is wasted on the query. In order to improve the performance of this program, the common practice is to store the results of the query in the program's memory.

ASP.net 2.0 provides a wide range of caching options. Web pages and user controls can be cached through output caching, and we can cache data at the control level through the ObjectDataSource and SqlDataSource controls, while ASP. NET's data cache provides a rich cache interface (caching API) for page developers to cache objects programmatically. In this article and the next 3 articles we will examine the cache properties of ObjectDataSource and data cache, and we will explore how to cache application-wide data at startup and by using SQL cache dependencies flush cached data.

Main cache points

Because caching increases the overall performance of a program by placing a copy of the data in a place that is easy to access. Because it is only a copy, the replica cannot synchronize updates when the source data changes. To do this, the page developer should develop a standard to clear out the memory, using one of the following 2 methods:

Time-based Standard: An entry (item) added to memory that can only reside fixed or flexible (sliding) for a period of time in memory. For example, a developer can set a time period, such as 60 seconds, when an entry is added to memory, no matter how often it is accessed, it is cleared after 60 seconds, and if it is flexible (sliding), when the last time it is accessed, it is cleared out once it has exceeded 60 seconds.

Dependency-based Standard: Assigns a subordinate body (Dependency) to memory when adding entries to it, and clears the entry when the corresponding subordinate body of the entry changes. The subordinate body can be a file, another cache entry, or simply a mixture of the two (combination) and, of course, the SQL cache dependencies, which can add entries to memory and clear the entries when the source data changes. We'll look at this in the next article, "Using SQL cache dependencies SqlCacheDependency."

Either way, we can access the entries before they are cleared. If the memory reaches its limit, it clears the existing entry and then adds a new entry. Therefore, it is important that when processing cached data, we should fully consider the possibility that the cached data has been purged. In the next article, "Caching data in a tiered architecture," we examine which mode to use to access data from memory.

Caching is an economical way to improve program performance, as Steven Smith explains in his article ASP.net caching:techniques and best practices: "Caching is getting ' Good ' performance is a great way to not need too much time and analysis. ... Memory is also cheap, to achieve your desired performance, by caching technology you need to spend 30 seconds, by optimizing the code and database you may take days or even weeks ...

While caching can be an obvious boost to system performance, it is not suitable for all applications, such as some real-time (real-time), frequently updated data programs.
But for most programs, it works. For more background information on the cache in ASP.net 2.0, refer to the Tutorials for caching section of the ASP.net 2.0 QuickStart performance series.

First step: Create caching page

Before we begin, let's take the time to add the pages that need to be used in the last four tutorials, including this article. Let's start by creating a new folder called Caching in the project, and next, add the following pages to the directory and configure to use the Site.master master page.

Default.aspx
Objectdatasource.aspx
Fromthearchitecture.aspx
Atapplicationstartup.aspx
Sqlcachedependencies.aspx


Figure 1: Creating the relevant asp.net page

Like other folders, the Default.aspx page in the caching folder shows the articles in this series. Remember that the user control Sectionleveltutoriallisting.ascx provides this functionality and drags it onto the page in design mode.


Figure 2: Adding a user control for the Default.aspx page Sectionleveltutoriallisting.ascx

Finally, add these pages to the Web.sitemap file, in particular, in the "Working with Binary Data" <SITEMAPNODE>: After:

 <sitemapnode title=" Caching "url=" ~/caching/default.aspx "description=" Learn Use the caching features of ASP.net 2.0. > <sitemapnode url= "~/caching/objectdatasource.aspx" title= "ObjectDataSource Caching" description= "how To cache data directly from the ObjectDataSource control. "/> <sitemapnode url=" ~/caching/fromthearchitecture.aspx "Title=" Caching in the Architecture "description=" is the "I" to cache data from within the architecture. "/> <site  Mapnode url= "~/caching/atapplicationstartup.aspx" title= Caching Data at Application Startup "description=" Learn Cache expensive or infrequently-changing queries at the start of the application. "/> <sitemapnode url=" ~/caching /sqlcachedependencies.aspx "title=" Using SQL Cache dependencies "description=" examine how to have data automatically exp IRE from the cache when it underlying database data is modified. "/> </siteMapNode> 

After completing the Web.sitemap file update, let us view in the browser, the left-hand menu bar displays the caching chapter article
Figure 3: Sitemap Site map contains articles for caching chapters

Step Two: Display the product in the Web page

This article examines how to use the ObjectDataSource control's built-in (built-in) caching capabilities. Before we start, we first need to create a page, use a ObjectDataSource control to invoke the PRODUCTSBLL class classes to get product information, and then display it with the GridView control.

First open the Objectdatasource.aspx page in the caching folder. Drag a GridView control from the toolbox to the page, set its ID to products, and then choose to bind it to a ObjectDataSource control from the smart tag, with an ID of Productsdatasource. Set the ObjectDataSource to use PRODUCTSBLL class classes.


Figure 4: Setting the ObjectDataSource control with the Productsbll class class

On this page, we want to create a GridView control that allows editing, and when the cached data in the ObjectDataSource control changes, we can see what happens in the GridView interface. Select the default GetProducts () method in the Select tab, but in the Update tab select the UpdateProduct () overload method that accepts ProductName, UnitPrice, and ProductID as input parameters.


Figure 5: Selecting the overloaded UpdateProduct () method in the Update tab

Finally, select (None) in the Insert and Delete tabs and click the Finish button. Once you complete the Set Data Source Wizard, Visual Studio sets the OldValuesParameterFormatString property of the ObjectDataSource control to original_{0}. As discussed in the previous tutorial Chapter 16, "Overview inserts, updates, and deletes data", the property is either deleted or set to {0}, or the update operation will report an error.

In addition, when you complete the wizard, Visual Studio adds all the data columns for the product to the GridView control, removing all bound columns (BoundFields) except ProductName, CategoryName, and UnitPrice. Then, change the HeaderText property of the 3 columns to product, Category, and Price respectively. Because ProductName is required, the ProductName column is transformed into a template column (TemplateField), and a RequiredFieldValidator control is added to the EditItemTemplate; Convert the UnitPrice column to a template column and add a CompareValidator control to ensure that the user enters a valid currency value that is greater than or equal to 0. In addition, you can make some improvements on the interface, such as centering the UnitPrice value, or making some formatting changes to UnitPrice's read-only and editing interfaces.

In the GridView of the smart tag point related items Start editing, paging, sorting function.

  Note: Do you want to review how to customize the editing interface for the GridView? Please refer to the previous article 20 "Custom Data modification Interface"


Figure 6: Enable the GridView editing, sorting, paging feature.

After the GridView modification is complete, the GridView and ObjectDataSource code declarations look like this:

<asp:gridview id= "Products" runat= "server" autogeneratecolumns= "False" datakeynames= "ProductID" datasourceid= " Productsdatasource "allowpaging=" true "allowsorting=" True "> <Columns> <asp:commandfield showeditbutton=
 "True"/> <asp:templatefield headertext= "Product" sortexpression= "ProductName" > <EditItemTemplate> <asp:textbox id= "ProductName" runat= "server" text= ' <%# Bind ("ProductName")%> ' ></asp:TextBox> < Asp:requiredfieldvalidator id= "RequiredFieldValidator1" display= "Dynamic" controltovalidate= "ProductName"
 Setfocusonerror= "True" errormessage= "You must provide a name for the product." runat= "Server" >*</asp:RequiredFieldValidator> </EditItemTemplate> <ItemTemplate> <asp:
 Label id= "Label2" runat= "server" text= ' <%# Bind ("ProductName")%> ' ></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:boundfield datafield= "CategoryName" headertext= "Category" readonly= "True" sortexpression= "CategoryName"/> <asp:templatefield headertext= "Price" sortexpression= "UnitPrice" > < edititemtemplate> $<asp:textbox id= "UnitPrice" runat= "Server" columns= "8" text= ' <%# ' Bind ("UnitPrice", "{0:N2 ")%> ' ></asp:TextBox> <asp:comparevalidator id=" CompareValidator1 "controltovalidate=" UnitPrice " Display= "Dynamic" errormessage= "You must enter a valid currency value with no currency symbols.
 Also, the value must is greater than or equal to zero. " Operator= "Greaterthanequal" setfocusonerror= "True" type= "Currency" runat= "server" valuetocompare= "0" >*</asp: comparevalidator> </EditItemTemplate> <itemstyle horizontalalign= "right"/> <ItemTemplate> < Asp:label id= "Label1" runat= "server" text= ' <%# Bind ("UnitPrice", "{0:c}")%> '/> </ItemTemplate> </as p:templatefield> </Columns> </asp:GridView> <asp:objectdatasource id= "Productsdatasource" runat= " Server "OldvaluespaRameterformatstring= "{0}" selectmethod= "GetProducts" typename= "PRODUCTSBLL" updatemethod= "UpdateProduct" > < updateparameters> <asp:parameter name= "ProductName" type= "String"/> <asp:parameter name= "UnitPrice" Type = "Decimal"/> <asp:parameter name= "ProductID" type= "Int32"/> </UpdateParameters> </asp:o Bjectdatasource>

As shown in Figure 7, the GridView lists the name, category, and price information for each product. Take a few minutes to test the page-sort the results, view the pagination, and edit a record.


Figure 7: Display the name, category, and price information for each record

Step three: Examine how ObjectDataSource requests data

The GridView with ID products retrieves and displays the data by calling the Select () method of the ObjectDataSource named Productsdatasource. The ObjectDataSource creates an instance of the Productsbll class class of the business logic layer and invokes its getproducts () method. The method also invokes the GetProducts () method of the data access layer productstableadapter. The data access layer connects to the database Northwind and executes the select query that has been set up. The query data is returned to the data access layer as Northwinddatatable, and the DataTable object is then passed back to the business logic layer, the ObjectDataSource, and the GridView control. The GridView control creates a GridViewRow object for each data row (DataRow) in the DataTable, and each GridViewRow object is eventually compiled into HTML to be returned to the client and rendered in the visitor's browser.

At any time, when the GridView control needs to be bound, it is executed in the order that the above events occur. For example, the first login page, the transfer of data from one page to another page, sorting in the GridView, and the modification of the data through the GridView built-in edit or delete interface. When the GridView view is set to Disabled, the GridView is also rebind every time the page is returned, and of course we can explicitly invoke the DataBind () method to enforce the binding on the GridView.

To more clearly reveal how often the data is retrieved from the database, we display a message indicating that the program is retrieving data at some point. To do this, add a Label control with ID odsevents on the GridView control, clear its Text property, and set its EnableViewState property to False. Add a button control below the label control to set its Text property to "postback".


Figure 8: Adding label and Button controls on the GridView

During the entire data retrieval process, the ObjectDataSource selecting event is first triggered and its corresponding set of methods is invoked. Create an event handler for the event and add the following code:

protected void Productsdatasource_selecting (object sender,
 ObjectDataSourceSelectingEventArgs e)
{
 Odsevents.text = "--selecting event fired";
}

Whenever ObjectDataSource begins retrieving data, the Label control displays the text "selecting event fired."

The page is accessed in the browser. When you first log on, the text "Selecting Event fired" is displayed. When you click the "Postback" button, we notice that the text disappears (if you set the GridView EnableViewState property to the default value true). This is because when the page is returned, the GridView is rebuilt (reconstructed) by loading the data into its view state, so no longer needs to retrieve the database through the ObjectDataSource to get the data rebuilt. However, sorting, paging, editing, and so on all cause the GridView to rebind to the data source, so the text "selecting event fired" appears again.


Figure 9: Displays the text "Selecting event fired" when the GridView is rebind to the data source


Figure 10: The dot "postback" button causes the GridView to get data from view state

It seems a waste of resources to retrieve data from the database every time you page and sort. Even if the GridView does not support sorting and paging, anyone who logs on to the page for the first time needs to retrieve data from the database (if the view state is set to disabled, the data will be retrieved every time the page is turned on). If the GridView is the same for all users, then additional database queries are wasteful. We can cache the data returned by the GetProducts () method and bind the GridView to those cached data.

Step Fourth: Cache data with ObjectDataSource

By simply setting certain properties, we can allow ObjectDataSource to automatically cache its retrieved data. The following summarizes the caching-related properties of the ObjectDataSource control:

enablecaching-must be set to True and false by default.

cacheduration-cache time, in seconds. The default is 0, and the ObjectDataSource control caches data only if the EnableCaching property is set to True and CacheDuration is set to a value greater than 0.

Cacheexpirationpolicy-can be set to absolute or sliding. If it is absolute, when it is set to a number of seconds, the ObjectDataSource caches the retrieved data for how many seconds, and if it is sliding, when it is set to a number of seconds, the cache is terminated once the cached data has not been accessed for more than a few seconds. Default is absolute.

Cachekeydependency-uses this property to associate a ObjectDataSource cache entry (entry) with an existing cache dependency. Allows it to clear the cache entry out of memory in advance. In most cases, you associate the SQL cache dependency with the ObjectDataSource cache with this attribute. This topic will be examined in a later tutorial, "Using SQL cache dependencies SqlCacheDependency."

Let's set the data cache time for the ObjectDataSource with ID productsdatasource to 30 seconds. Set its EnableCaching property to True, and set its CacheDuration property to the 30;cacheexpirationpolicy property as the default absolute.


Figure 11: Set the ObjectDataSource cache time to 30 seconds

Save your settings and view them in your browser. When you first log on to the page, the text "Selecting Event fired" is displayed because the original data has not yet been cached. But you click the "Postback" button, or for paging, sorting, or point edit, Cancel button, the text "Selecting event fired" will not be displayed. The reason is that the selecting event is triggered only when the ObjectDataSource control retrieves data, and the selecting event is not triggered if the ObjectDataSource control is fetching data from the cache.

After 30 seconds, the data is purged from memory, or the data is cleared when the insert, Update, or Delete method of the ObjectDataSource control is invoked. Therefore, after 30 seconds or click the "Update" button, edit, cancel the button, or sorting, pagination will prompt ObjectDataSource to retrieve data, triggering selecting events, the text "Selecting event fired" will be displayed. 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 that ObjectDataSource adds to memory may be erased. If ObjectDataSource does not or only occasionally cache data, close some applications to free up memory, and then try again.

Figure 12 shows the caching process for the ObjectDataSource. When the text "Selecting event fired" appears on the screen, it is because the data is not found in the cache and must be retrieved. When the text disappears, it is because the data is cached. When the required data is obtained from the cache, no data query is executed.


Figure 12:objectdatasource Storing and retrieving data in the cache

Each asp.net application has its own instance of data caching that all pages and users can access. That means that for data cached by the ObjectDataSource control, all users who log on to the page can access it. To make a validation, open the Objectdatasource.aspx page in a browser, and when you first log on to the page, the text "Selecting Event fired" appears (assuming that the data that was cached at the previous test has been cleared away). 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 the data from the first browser page cache.

When you add the retrieval data to memory, ObjectDataSource uses a value called Cache key, which includes the values of the CacheDuration and CacheExpirationPolicy properties The type of the business object that is invoked, specified by the TypeName property (for example, PRODUCTSBLL), and the value of the SelectMethod property, ObjectDataSource. And the values of the name and Values;startrowindex and Maximumrows properties of the parameters in the SelectParameters parameter set, which are used to perform user-defined pagination (custom paging).

These attribute values are grouped together to form the cache key value to provide a unique identity value for each cached entry. For example, in the previous tutorial, we used the Getproductsbycategoryid (CategoryID) method of the Productsbll class to get all the products of a given class. If a user looks at the product information for a beverage class (with a CategoryID value of 1) on the page, if the ObjectDataSource control ignores the SelectParameters value while the data cache is being cached, when another user logs on to the page to view the product information of the condiment class, Just as the beverage product information is cached in memory, the second user will see the product information of the beverage category rather than the product information of the condiment class he wants. Therefore, when the cache key value contains Electparameters value, the ObjectDataSource can distinguish the condiment from the beverage class when the data is cached.

Data Update not synchronized (stale) problem

When you call the ObjectDataSource control's insert, update, and delete one of the methods, it clears the cache entry from memory. The advantage of this is that the cached old data is purged when the data is modified from the page. However, ObjectDataSource may still show the "not updated data" (that is, the source data has changed and the cached data is not synchronized). The simplest example is to modify data directly from a database, such as a database administrator running a script to modify certain records in the database.

Here, we explore a delicate situation. While invoking the ObjectDataSource data modification method, it clears the cached data, but clears the cached entries that match the ObjectDataSource's property combination value (combination of properties) ( such as CacheDuration, TypeName, SelectMethod, etc.). 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 corresponding cached data for that row, the second Objectdatasources control still uses the corresponding cached data for that row. Let's do a validation, create a page that contains an editable GridView control, its corresponding ObjectDataSource control set to use caching, and call the Productsbll class's GetProducts () method to get the data. Add the GridView and ObjectDataSource controls on this page (or create another page), but set the second ObjectDataSource control to invoke the Getproductsbycategoryid (CategoryID) method. Because the SelectMethod properties of these 2 ObjectDataSource controls are different, they each have different cache values. If you edit a product in the first GridView control and then rebind the data (such as paging, sorting, and so on) in the second GridView control, we see in the second GridView control that the value of the product is still "old cached data" ( Instead of the first GridView control's modified value)

In short, if you are willing to use "old cache data", then only use the time based cache time value (time-based expiries, that is, set the specific length of the cache), if the data in a timely manner to update the requirements of high, the cache time set a short point. If you are not allowed to use "Old cached data", either discard the cache or use SQL cache dependencies (you can think of it as your cached database data). We'll explore SQL cache dependencies later.

Summarize:

In this paper, we examine the caching capabilities of ObjectDataSource. With only a few properties set, we can cache the data that ObjectDataSource calls the SelectMethod method. Its cacheduration and CacheExpirationPolicy properties specify the time and type of the cache (absolute or sliding). The Cachekeydependency property associates the ObjectDataSource cache entity with an existing cache slave (cache dependency), typically the SQL cache dependencies.

Because ObjectDataSource is simply caching data, we can programmatically implement this functionality in ObjectDataSource. This does not make sense in the presentation layer, however, because the ObjectDataSource control provides this functionality. But we can implement caching at other levels of the architecture. To do this, we need a logic that is the same as the ObjectDataSource call. In the next article, we'll examine how to programmatically process data caching within the architecture.

I wish you a happy programming!

Author Introduction

Scott Mitchell, author of this series of tutorials, 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.