protected void srcMovies_Selectingobject sender, ➥SqlDataSourceSelectingEventArgs e { lblMessage.Text = “Retrieving data from database”; } Cache SqlDataSource In Listing 9
Trang 1LISTING 9.29 DynamicImage.ashx
<%@ WebHandler Language=”C#” Class=”DynamicImage” %>
using System.Data;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
/// <summary>
/// Displays an image corresponding to the Id passed
/// in a query string field
/// </summary>
public class DynamicImage : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
// Get the Id of the image to display
string imageId = context.Request.QueryString[“Id”];
// Use SqlDataSource to grab image bytes
SqlDataSource src = new SqlDataSource();
src.ConnectionString =
WebConfigurationManager.ConnectionStrings[“Images”].ConnectionString;
src.SelectCommand = “SELECT Image FROM Images WHERE Id=” + imageId;
// Return a DataView
DataView view = (DataView)src.Select(DataSourceSelectArguments.Empty);
context.Response.BinaryWrite( (byte[])view[0][“Image”]);
// Return a DataReader
//src.DataSourceMode = SqlDataSourceMode.DataReader;
//IDataReader reader =
(IDataReader)src.Select(DataSourceSelectArguments.Empty);
//reader.Read();
//context.Response.BinaryWrite((byte[])reader[“Image”]);
//reader.Close();
}
public bool IsReusable
Trang 2get
{
return false;
}
}
}
In the ProcessRequest() method, an instance of the SqlDataSource control is created
The SqlDataSource control’s ConnectionString and SelectCommand properties are
initial-ized Finally, the SqlDataSource control’s Select() command is executed, and the results
are rendered with the Response.BinaryWrite() method
The return value from the Select() method is cast explicitly to a DataView object You
need to cast the return value to either a DataView or IDataReader for it to work with the
results of the Select() method
In Listing 9.29, the image bytes are returned in a DataView To illustrate how you can use
the Select() method to return a DataReader, I also included the code for returning the
image with a DataReader, but I added comments to the code so that it won’t execute
Caching Database Data with the SqlDataSource
Control
The easiest way to dramatically improve the performance of a database-driven website is
through caching Retrieving data from a database is one of the slowest operations that you
can perform in a web page Retrieving data from memory, on the other hand, is lightning
fast The SqlDataSource control makes it easy to cache data in your server’s memory
Caching is discussed in detail in Chapter 29, “Caching Application Pages and Data.” In
that chapter, you learn about all the different caching options supported by the
SqlDataSource control However, because it is so easy to cache data with the
SqlDataSource control and caching has such a dramatic impact on performance, I want
to provide you with a quick sample of how you can use the SqlDataSource control to
cache data
The page in Listing 9.30 displays a list of movies cached in memory
LISTING 9.30 CacheSqlDataSource.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<script runat=”server”>
Trang 3protected void srcMovies_Selecting(object sender,
➥SqlDataSourceSelectingEventArgs e)
{
lblMessage.Text = “Retrieving data from database”;
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Cache SqlDataSource</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:Label
id=”lblMessage”
EnableViewState=”false”
Runat=”server” />
<br /><br />
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
Runat=”server” />
<asp:SqlDataSource
id=”srcMovies”
EnableCaching=”True”
CacheDuration=”3600”
SelectCommand=”SELECT * FROM Movies”
ConnectionString=”<%$ ConnectionStrings:Movies %>”
Runat=”server” OnSelecting=”srcMovies_Selecting” />
</div>
</form>
</body>
</html>
In Listing 9.30, two properties of the SqlDataSource control related to caching are set
First, the EnableCaching property is set to the value True Next, the CacheDuration
prop-erty is set to a value that represents 3,600 seconds (1 hour) The movies are cached in
memory for a maximum of 1 hour If you don’t supply a value for the CacheDuration
property, the default value is Infinite
Trang 4WARNING
You need to understand that there is no guarantee that the SqlDataSource control will
cache data for the amount of time specified by its CacheDuration property Behind the
scenes, the SqlDataSource control uses the Cache object for caching This object
sup-ports scavenging When memory resources become low, the Cache object automatically
removes items from the cache
The page in Listing 9.30 includes a srcMovies_Selecting() event handler This handler is
called only when the movies are retrieved from the database rather than from memory
In other words, you can use this event handler to detect when the movies are dropped
from the cache (see Figure 9.15)
The page in Listing 9.30 illustrates only one type of caching that you can use with the
SqlDataSource control In Chapter 29, you learn about all the advanced caching options
supported by the SqlDataSource control For example, by taking advantage of SQL cache
dependencies, you can reload the cached data represented by a SqlDataSource control
automatically when data in a database is changed For more information, see the final
section of Chapter 25, “Using the ASP.Net URL Routing Engine.”
FIGURE 9.15 Caching the data represented by a SqlDataSource control
Trang 5Summary
In this chapter, you learned how to use the SqlDataSource control to connect and execute
commands against a SQL relational database In the first section, you learned how to
represent database connection strings with the SqlDataSource control You learned how to
store connection strings in the web configuration file and encrypt the connection strings
Next, you learned how to execute both inline SQL commands and stored procedures You
also learned how to cancel commands and handle errors gracefully
This chapter also discussed the different types of ASP.NET parameters that you can use
with the SqlDataSource control You learned how to use the Parameter,
ControlParameter, CookieParameter, FormParameter, ProfileParameter,
SessionParameter, and QueryStringParameter objects
Finally, you learned how to improve the performance of your database-driven applications
through caching You learned how you can cache the data represented by a SqlDataSource
control in server memory and avoid accessing the database with each page request
Trang 6Using List Controls .. Overview of the List ControlsWorking with the
DropDownList Control Working with the RadioButtonList Control Working with the ListBox Control
Working with the CheckBoxList Control Working with the BulletedList Control Creating a Custom List Control Summary
The List controls enable you to display simple lists of
options For example, you can use the RadioButtonList
control to display a group of radio buttons or the
BulletedList control to display a list of links
In this chapter, you learn how to use each of the List
controls included in the ASP.NET Framework In particular,
we discusses the DropDownList, RadioButtonList, ListBox,
CheckBoxList, and BulletedList controls You learn how to
bind the different types of List controls to a data source
such as a database table You also learn how to work
directly with the list items contained by a List control
Finally, at the end of this chapter, you learn how to build a
custom List control We create a client-side multiselect List
control that enables you to select multiple list items at a
time
Overview of the List Controls
The five List controls inherit from the base ListControl
class This means that all the List controls share a common
set of properties and methods This section provides you
with an overview of the common features of the List
controls
Declaring List Items
The List controls render a list of options Each option is
represented by an instance of the ListItem class For
example, you can use the page in Listing 10.1 to render
a set of options for selecting your favorite movie (see
Figure 10.1)
Trang 7LISTING 10.1 FavoriteMovie.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Favorite Movie</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:Label
id=”lblMovies”
Text=”Favorite Movie:”
AssociatedControlID=”rblMovies”
Runat=”server” />
FIGURE 10.1 Displaying a list of movies
Trang 8<asp:RadioButtonList
id=”rblMovies”
Runat=”server”>
<asp:ListItem
Text=”The Remains of the Day”
Value=”movie1” />
<asp:ListItem
Text=”Star Wars”
Value=”movie2” />
<asp:ListItem
Text=”Pulp Fiction”
Value=”movie3” />
</asp:RadioButtonList>
</div>
</form>
</body>
</html>
The page in Listing 10.1 contains a RadioButtonList control that contains three ListItem
controls that correspond to the three radio buttons All the List controls use the ListItem
control to represent individual list items
The ListItem control supports the following five properties:
Attributes—Enables you to add HTML attributes to a list item
Enabled—Enables you to disable a list item
Selected—Enables you to mark a list item as selected
Text—Enables you to specify the text displayed by the List Item
Value—Enables you to specify a hidden value associated with the List Item
You use the Text property to indicate the text that you want the option to display, and
the Value property to indicate a hidden value associated with the option For example, the
hidden value might represent the value of a primary key column in a database table
The Selected property enables you to show a list item as selected Selected radio buttons
and check boxes appear checked The selected option in a DropDownList is the default
option displayed Selected options in a ListBox appear highlighted And in the case of a
BulletedList control, the selected property has no effect whatsoever
The Enabled property has different effects when used with different List controls When
you set a ListItem control’s Enabled property to the value False when using the
DropDownList or ListBox controls, the list item is not rendered to the browser When you
use this property with a CheckBoxList, RadioButtonList, or BulletedList control, the
list item is ghosted and nonfunctional
Trang 9Binding to a Data Source
You can bind any of the List controls to a data source The List controls support both
declarative databinding and programmatic databinding
For example, the page in Listing 10.2 contains a DropDownList control bound to the
Movies database table with declarative databinding (see Figure 10.2)
FIGURE 10.2 Displaying list items with declarative databinding
LISTING 10.2 DeclarativeDataBinding.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Declarative DataBinding</title>
</head>
<body>
Trang 10<form id=”form1” runat=”server”>
<div>
<asp:DropDownList
id=”ddlMovies”
DataSourceID=”srcMovies”
DataTextField=”Title”
DataValueField=”Id”
Runat=”server” />
<asp:SqlDataSource
id=”srcMovies”
SelectCommand=”SELECT Id, Title FROM Movies”
ConnectionString=”<%$ ConnectionStrings:Movies %>”
Runat=”server” />
</div>
</form>
</body>
</html>
The DropDownList control’s DataSourceID property points to the ID of the SqlDataSource
control When you open the page in Listing 10.2, the SqlDataSource control retrieves the
records from the Movies database table The DropDownList control grabs these records
from the SqlDataSource control and creates a ListItem control for each data item
The DropDownList control has both its DataTextField and DataValueField properties set
When the DropDownList control creates each of its list items, it uses the values of the
DataTextField and DataValueField properties to set the Text and Value properties of
each list item
As an alternative to declarative databinding, you can programmatically bind any of the
List controls to a data source For example, the page in Listing 10.3 binds a ListBox
control to a collection that represents a shopping cart (see Figure 10.3)