Querying Data
Now that you can control access to your application, you can turn your attention to
querying and maintaining data. You will useWeb Server Data controls to connect to the
database, query data, and maintain the data, in a manner similar to that used by the
Windows Forms application you built in Chapter 24, “Working with Data Binding and
DataSets.”
Displaying Customer Information
In the following exercises, you will fetch all of the rows in the Customers table in the
Microsoft SQL Server Northwind Traders database and display them in a GridView. The
first task is to create a connection that you can use to connect to the Northwind database.
NOTE
This exercise assumes that you have completed the exercises in Chapter 23, “Using a
Database,” on your computer.
Create a connection to the Northwind Database
1. Display the CustomerData.aspx page in the Design View window. Delete the label
displaying “This form will be implemented later.”
2. In the Toolbox, expand the Data category. Add a SqlDataSource control to the
Web form.
3. Click anywhere in the form to hide the SqlDataSource Tasks menu that appears. A
control called SqlDataSource1 is added to the Web form. The SqlDataSource
control is a Web Server control that performs the same tasks as a data source in a
Windows Forms application.
NOTE
Although the SqlDataSource control appears on the Web form at design time, it
will not be visible when the Web form runs.
4. Using the Properties window, change the (ID) property of SqlDataSource1 to
CustomerInfoSource.
5. Select the CustomerInfoSource control on the Web Form. Click the Smart Tag
icon to display the SqlDataSource Tasks menu, and then click the Configure Data
Source link.
The Configure Data Source Wizard appears. This is very similar (but not identical)
to the wizard you saw in Chapter 23. You will use it to create a connection to the
database and fetch the data from the Customers table.
6. Click the New Connection button. Use the Add Connection page to create a new
connection with the values shown in the following table. Click OK when you have
finished.
Prompt Response
Data source Microsoft SQL Server (SqlClient)
Server name YourServer\SQLExpress
Log on to the server Use windows authentication
Select or enter a database name Northwind
7. In the Configure Data Source Wizard, click Next.
8. In the Save the Connection String to the Application Configuration file screen,
save the connection string as NorthwindConnectionString and click Next.
9. In the Configure the Select Statement page, ensure “Specify columns from a table
or view” is selected. Select the Customers table in the Name drop-down list box.
In the Columns list box, check “*”.
10. Click Advanced. In the Advanced SQL Generation Options dialog box, check
“Generate INSERT, UPDATE, and DELETE statements.” Click OK, and then
click Next.
NOTE
If you don't select “Generate INSERT, UPDATE, and DELETE statements,” you
will still be able to modify the data in the DataSet retrieved by the data source, but
you won't be able to send these changes back to the database. You can always add
commands to modify the database after creating the data source by modifying its
DeleteQuery, InsertQuery, and UpdateQuery properties and providing the
appropriate SQL statements.
11. In the Test Query page, click Test Query.
The data from the Customers table appears in the grid in the dialog box.
12. Click Finish.
13. Click the Smart Tag icon to hide the SqlDataSource Tasks menu.
In the next exercise, you will add a GridView control to the CustomerData Web form and
bind it to the CustomerInfoSource data source.
Lay out the CustomerData Web form
1. In the Toolbox, click the GridView control. Drag it onto the form. Click anywhere
on the form to hide the GridView Tasks menu that appears.
A GridView is added to the form and displays placeholder data. Resize the
GridView so that it fills most of the form.
2. Using the Properties window, change the (ID) property of the GridView control to
CustomerGrid.
3. With the GridView control still selected, click the Smart Tag icon to display the
GridView Tasks menu. In the GridView Tasks menu, click the Auto Format link.
4. In the Auto Format dialog box, select the Classic scheme and then click OK.
TIP
If you don't like any of the predefined formats available in the Auto Format dialog
box, you can change the styles of the elements of a GridView control manually by
using the properties in the Properties window. BackColor, BorderStyle,
BorderWidth, FooterStyle, HeaderStyle, and RowStyle are the most commonly
modified properties.
5. In the GridView Tasks menu that is still displayed, select CustomerInfoSource
from the Choose Data Source drop-down list.
The column headings for the Customers table appear in the GridView control on
the screen.
6. Click the Smart Tag icon to hide the GridView Tasks menu.
Test the CustomerData form
1. On the Debug menu, click Start Without Debugging.
Internet Explorer starts and displays the Log In page.
2. Log in as John with password Pa$$w9rd.
The CustomerData page appears displaying the details of every customer in the
database:
Notice that the page is currently read-only; you cannot modify any of the details
displayed. You will enhance the Web form later in this chapter to enable the user
to make changes.
3. Close Internet Explorer when you have finished browsing the data and return to
Visual Studio 2005.
Web Site Security and SQL Server
When you use the ASP.NET Development Server to run an application that uses Forms-
based security, it executes in the context of the account you are using to run Visual
Studio 2005. Assuming you used the same account to create the Northwind database,
then the Web application should have no problems accessing the database.
However, if you deploy the Web site to IIS the situation changes. IIS runs applications
that use Forms-based security using the ASPNET account. This account has very few
privileges by default, for security purposes. In particular, it will not be able to connect to
SQL Server Express and query the Northwind database. Therefore you will need to grant
the ASPNET account login access to SQL Server Express and add it as a user to the
Northwind database. For more details, see the sp_grantlogin and sp_grantdbaccess
commands in the MSDN Library for Visual Studio 2005.
Displaying Data in Pages
Fetching the details of every customer is very useful, but suppose there are a large
number of rows in the Customers table. It is highly unlikely that a user would actively
want to browse thousands of rows, so generating a long page displaying them all would
be a waste of time and network bandwidth. Instead, it would be far better to display data
in chunks and allow the user to page through that data. This is what you will do in the
following set of exercises.
Modify the GridView to use paging
1. Ensure that CustomerData.aspx is displayed in the Design View window. Select
the CustomerGrid control. In the Properties window, set the AllowPaging property
to True.
A footer is added to the GridView containing a pair of page numbers. This footer
is referred to as the pager. You can format the pager in many different ways. The
style shown is the default format, comprising page numbers that the user can click.
2. In the Properties window, set the PageSize property to 8.
This will cause the GridView to display data in eight-row chunks.
3. Expand the PagerStyle composite property. You can use this property to specify
how the pager should be formatted. Set HorizontalAlign sub-property to Left.
The numbers in the pager move to the left marginin the GridView control.
4. Expand the PagerSettings composite property. Use the values in this property to
specify how page navigation links are formatted. You can specify page navigation
links in two ways: as page numbers, or as next/previous page arrows. Set the
Mode property to NumericFirstLast to display page numbers with the first and last
page arrows displayed to enable the user to move quickly to the start or end of the
data. Set the PageButtonCount sub-property to 5; this will cause page links to be
displayed in groups of five (you will see what this does when you run the Web
application).
If you want to use next/previous page arrows, you can change the default text
displayed (“>” and “<”) by modifying the values of the NextPageText and
PreviousPageText properties. Similarly, you can change the text displayed for the
first and last page links by editing the FirstPageText and LastPageText properties.
Notice that the values in these properties require encoding as HTML characters;
otherwise, they will not be displayed properly (for example, the “>” symbol is
specified as “>”). If you prefer, you can also specify the name of an image file
in the FirstPageImageUrl, LastPageImageUrl, PreviousPageImageUrl and
NextPageImageUrl properties. The page navigation links will appear as buttons
containing these images if supported by the browser.
5. Run the Web application.
After logging in, the first eight rows of data and a set of page links are displayed
on the CustomerData Web form. Page numbers 1, 2, 3, 4, and 5 are displayed,
together with “>>” to move directly to the last page. Clicking the “…” link
displays the next five page numbers together with a “<<” link for moving directly
back to the first page. An additional “…” link provides access to the previous five
pages.
6. Click the links at the bottom of the grid to move from page to page.
7. Close Internet Explorer and return to the Visual Studio 2005 programming
environment when you have finished browsing the data.
Optimizing Data Access
In this chapter, you have been using a SqlDataSource control to connect to the database
and fetch the data. Behind the scenes, the SqlDataSource control creates a DataSet. When
you bind a Web Server Data control such as GridView to a data source, Visual Studio
2005 generates code that populates the DataSet and displays it in the data control.
DataSets are very powerful objects. You have seen in earlier chapters how they can act as
in-memory datastore and how you can use them to update a database. However, this
power comes at a price. A DataSet that contains a large number of rows will itself be very
large and can consume considerable resources. If you are using a GridView to simply
display data rather than modify it, using a DataSet may be too cumbersome a solution.
The SqlDataSource control has a property called DataSourceMode which you can set to
DataSet (the default) or DataReader. Specifying a value of DataReader causes the data
source to open an ADO.NET DataReader object for retrieving data. A DataReader
implements a very efficient mechanism for fetching data as a read-only stream. For more
information, see the sidebar “Firehose Cursors” in Chapter 23. However, one drawback
of using a DataReader is that it does not support paging.
Caching Data in a Data Source
A DataSet contains a copy of the data it fetches. The longer the DataSet is held, the more
out-of-date the information it holds can become. How can you make certain that the data
a user sees in a Web form is the current data without continually refilling the DataSet? If
you examine the SqlDataSource control, you will find that it has three properties that you
can use to help solve this problem:
• EnableCaching.
Whenever you display a Web form that contains a SqlDataSource control, the
SQL SELECT statement specified by that control is executed to populate its
DataSet. By default, if you use paging to display, and the rows displayed are
spread over several pages, the SQL SELECT statement will be executed whenever
you move from one page to another. The SQL SELECT statement will also be
executed again if you simply refresh the view of the Web form in the browser. In
this way, you are always presented with a copy of the data that is up-to-date when
the Web form is displayed.
However, if none of the data actually changes between displaying or refreshing
pages, you are wasting database resources by repeatedly connecting to and
querying the database. If you set the EnableCaching property to True, the DataSet
will act as a cache and the SQL SELECT statement will only be re-executed based
on the settings of two other properties: CacheDuration, and
CacheExpirationPolicy.
• CacheDuration.
This property specifies how frequently the SQL SELECT statement is re-executed
and the cache refreshed. Its default setting of Infinite means that the cache never
expires and so will never be refreshed. Setting it to a numeric value specifies the
expiration period of the cache, in seconds.
• CacheExpirationPolicy.
This property is used in conjunction with CacheDuration to determine how
frequently the cache is updated. If this property is set to its default value of
Absolute, then the cache will always be refreshed every CacheDuration seconds. If
this property is set to Sliding, then the cache will only be refreshed after
CacheDuration seconds of inactivity in the application.
IMPORTANT
You can only set the EnableCaching property to True if the DataSourceMode property of
the SqlDataSource is set to DataSet. If the DataSourceMode property is set to
DataReader, the application will throw an exception when the page is displayed.
TIP
Caching can protect you from temporary database failure. If caching is disabled, the
SqlDataSource control must connect to the database whenever a page is displayed. If the
database is unavailable, this connection will fail and the SqlDataSource will throw an
exception. However, if caching is enabled, and the data in the cache has not yet expired,
you will be able to move to another page and display the cached data. If the
CacheDuration and CacheExpirationPolicy properties are set to suitable values, it may
even be possible to recover the database without too many users even noticing.
In the next exercise, you will see the effects of modifying the cache settings of a
SqlDataSource control.
Investigate caching with a SqlDataSource object
1. Ensure that CustomerData.aspx is displayed in the Design View window. Select
the CustomerInfoSource control. In the Properties window, set the EnableCaching
property to True. Verify that the CacheDuration property is set to Infinite, and the
CacheExpiration Policy property is set to Absolute.
This combination of settings causes the DataSet generated by the SqlDataSource
control to act as a cache that never expires. The cache will be populated when the
Web form is first displayed, but will never be refreshed when moving from page
to page or refreshing the Web form.
2. Run the Web application. Log in and display the first page of Customer data.
Notice that the value in the City column of the first row (ALFKI) is Berlin.
3. Leave the Web application running, and open a Command Prompt window. In the
Command Prompt window, type the following command:
sqlcmd –S YourServer\SQLExpress –E
Replace YourServer with the name of your computer. This command starts the
SQL Server command line tool, allowing you to connect to a database and run
SQL statements.
A 1> prompt is displayed by the sqlcmd tool.
4. At the 1> prompt, type the following statements (the prompt will change each time
you press the Enter key):
5. USE Northwind
6. GO
7. UPDATE Customers SET City = 'Bonn' WHERE CustomerID = 'ALFKI'
GO
The message (1 row affected) is displayed. This command changes the value of
the City column for the first customer from Berlin to Bonn.
8. Leave the Command Prompt window open and return to the Web application
running in Internet Explorer. Move to page 2, and then return to page 1. Notice
that the City for the first row has not changed—it is still Berlin. Close the Web
application and return to Visual Studio 2005.
9. Select the CustomerInfoSource control again. In the Properties window, set the
Cache Duration property to 10 (ensure EnableCaching is still set to True).
The DataSet generated by the SqlDataSource control now expires after 10
seconds, and will be updated. You will see the changes if you redisplay the page
after the expiration period.
10. Run the Web application again. Log in and display the first page of Customer data.
Notice that the value in the City column of the first row (ALFKI) is now Bonn
(this is the change you made earlier).
11. Return to the sqlcmd tool running in the Command Prompt window. At the 1>
prompt, type the following statements:
12. UPDATE Customers SET City = 'Munich' WHERE CustomerID = 'ALFKI'
GO
The message (1 row affected) is displayed again. This command changes the value
of the City column for the first customer from Bonn to Munich.
13. Wait for more than 10 seconds and then return to the Web application running in
Internet Explorer. Move to page 2, and then return to page 1. Notice that the City
for the first row has changed to Munich as the DataSet has been refreshed. Close
the Web application.
14. Close the Command Prompt window.
. to
DataSet (the default) or DataReader. Specifying a value of DataReader causes the data
source to open an ADO.NET DataReader object for retrieving data. . using a DataReader is that it does not support paging.
Caching Data in a Data Source
A DataSet contains a copy of the data it fetches. The longer the DataSet