Binding to a DataReader Typically, you use the ObjectDataSource control to represent database data.. For example, the component in Listing 18.3, the MovieDataReader component, returns al
Trang 1In Listing 18.2, the ObjectDataSource control includes two properties named TypeName
and SelectMethod The TypeName property contains the name of the component that you
want to represent with the ObjectDataSource control The SelectMethod property
repre-sents the method of the component that you want to call when selecting data
The GridView control is bound to the ObjectDataSource control through its DataSourceID
property When you open the page in Listing 18.2, the list of movies is retrieved from the
MovieCollection component and displayed in the GridView
The MovieCollection component contains instance methods The ObjectDataSource
automatically creates a new instance of the MovieCollection component before calling its
GetMovies() method It automatically destroys the object after it finishes using the object
You also can use the ObjectDataSource control to call shared (static) methods In that
case, the ObjectDataSource doesn’t need to instantiate a component before calling the
method
Binding to a DataReader
Typically, you use the ObjectDataSource control to represent database data The NET
Framework provides you with multiple ways of representing data This section discusses
how you can use an ObjectDataSource to represent a DataReader
NOTE
The different ADO.NET objects are compared and contrasted in Chapter 19, “Building
Data Access Components with ADO.NET.”
The ADO.NET DataReader object provides you with a fast, read-only representation of
database data If you need to retrieve database records in the fastest possible way, you
should use a DataReader object
For example, the component in Listing 18.3, the MovieDataReader component, returns all
the movies from the Movies database table by using the SqlDataReader object The
component imports the System.Data.SqlClient namespace to use this Microsoft SQL
Server-specific ADO.NET object
LISTING 18.3 MovieDataReader.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public class MovieDataReader
{
private readonly string _conString;
Trang 2public SqlDataReader GetMovies()
{
// Create Connection
SqlConnection con = new SqlConnection(_conString);
// Create Command
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = “SELECT Id,Title,Director FROM Movies”;
// Return DataReader
con.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
public MovieDataReader()
{
_conString =
➥WebConfigurationManager.ConnectionStrings[“Movies”].ConnectionString;
}
}
The component in Listing 18.3 actually uses three ADO.NET objects: Connection, Command,
and DataReader The SqlCommand object uses the SqlConnection object to connect to the
database The records are returned from the SqlCommand object and represented by the
SqlDataReader object
The WebConfigurationManager class retrieves the database connection string from the web
configuration file To use this class, you need to import the System.Web.Confiugration
namespace (and have a reference to the System.Web.dll assembly)
The ObjectDataSource control in Listing 18.4 represents the MovieDataReader object It
binds the movies to a GridView control
LISTING 18.4 ShowMovieDataReader.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>Show Movie DataReader</title>
</head>
<body>
<form id=”form1” runat=”server”>
Trang 3<div>
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
Runat=”server” />
<asp:ObjectDataSource
id=”srcMovies”
TypeName=”MovieDataReader”
SelectMethod=”GetMovies”
Runat=”server” />
</div>
</form>
</body>
</html>
Binding to a DataSet
You also can use the ObjectDataSource when you need to represent an ADO.NET
DataSet Using a DataSet is slower than using a DataReader; however, you can perform
advanced operations, such as filtering and sorting, on data represented with a DataSet
The component in Listing 18.5 returns all the records from the Movies database table
However, it uses a DataSet instead of a DataReader object
LISTING 18.5 MovieDataSet.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public class MovieDataSet
{
private readonly string _conString;
public DataSet GetMovies()
{
// Create DataAdapter
string commandText = “SELECT Id,Title,Director FROM Movies”;
SqlDataAdapter dad = new SqlDataAdapter(commandText, _conString);
Trang 4// Return DataSet
DataSet dstMovies = new DataSet();
using (dad)
{
dad.Fill(dstMovies);
}
return dstMovies;
}
public MovieDataSet()
{
_conString =
➥WebConfigurationManager.ConnectionStrings[“Movies”].ConnectionString;
}
}
The component in Listing 18.5 uses two ADO.NET objects: DataAdapter and DataSet The
SqlDataAdapter represents the SQL select command and populates the DataSet with the
results of executing the command The WebConfigurationManager class reads the database
connection string from the web configuration file
The page in Listing 18.6 binds the list of movies to a DropDownList control
LISTING 18.6 ShowMovieDataSet.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>Show Movie DataSet</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
Runat=”server” />
<asp:ObjectDataSource
id=”srcMovies”
TypeName=”MovieDataReader”
Trang 5SelectMethod=”GetMovies”
Runat=”server” />
</div>
</form>
</body>
</html>
Binding to a LINQ to SQL Query
LINQ to SQL is the preferred method of data access in NET Framework The expectation is
that you will use LINQ to SQL instead of ADO.NET to interact with a database Chapter
20, “Data Access with LINQ to SQL,” is devoted to the topic of LINQ to SQL
Here’s a quick sample of binding an ObjectDataSource to a component that represents a
LINQ to SQL query The component that contains the LINQ query is contained in
Listing 18.7
LISTING 18.7 Employee.cs
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
public partial class Employee
{
public static IEnumerable<Employee> Select()
{
EmployeesDataContext db = new EmployeesDataContext();
return db.Employees.OrderBy( e=>e.LastName );
}
}
Before you can use the component in Listing 18.7, you first must create the
EmployeesDataContext The easiest way to create the DataContext is to select Website,
Add New Item and select the LINQ to SQL Classes template Name the LINQ to SQL
Classes Employees.
After the LINQ to SQL Designer appears, drag the Employees database table onto the
Designer surface from the Database Explorer window At this point, the
EmployeesDataContext will be ready
Trang 6The page in Listing 18.8 contains an ObjectDataSource that represents the Employee class
LISTING 18.8 ShowLINQ.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>Show LINQ</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:GridView
id=”grdEmployees”
DataSourceID=”srcEmployees”
runat=”server” />
<asp:ObjectDataSource
id=”srcEmployees”
TypeName=”Employee”
SelectMethod=”Select”
Runat=”server” />
</div>
</form>
</body>
</html>
Binding to a Web Service
Web services enable you to share information across the Internet When you
communi-cate with a remote web service, you use a local proxy class to represent the web service
located on the remote machine You can use the ObjectDataSource to represent this proxy
class
For example, the file in Listing 18.9 contains a simple web service that returns the current
server time You can create this file in Visual Web Developer by selecting Web Site, Add
New Item, and selecting the Web Service item
Trang 7LISTING 18.9 TimeService.asmx
<%@ WebService Language=”C#” Class=”TimeService” %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace = “http://tempuri.org/”)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TimeService : System.Web.Services.WebService {
[WebMethod]
public DateTime GetServerTime() {
return DateTime.Now;
}
}
After you create the web service in Listing 18.9, you can communicate with the service
from anywhere in the world (or the galaxy or the universe) Just as long as a computer is
connected to the Internet, the computer can call the GetServerTime() method
Before you can call the web service, you need to create a web service proxy class If you
use Visual Web Developer, select Web Site, Add Web Reference and enter the URL of the
TimeService.asmx file (You can click the Web Services in This Solution link to list all the
web services in your current project.) Change the name of the web reference to
LocalServices and click Add Reference (see Figure 18.1)
NOTE
If you are not using Visual Web Developer, you can create a web service proxy class
from the command line by using the Wsdl.exe (Web Services Description Language)
tool
When you click Add Reference, a new folder is added to your project named
App_WebReferences The App_WebReferences folder contains a subfolder named
LocalServices Finally, your web configuration file is updated to include the URL to the
TimeService web service
Now that we have a consumable web service, we can represent the Web service using the
ObjectDataSource control The page in Listing 18.10 displays the server time using a
FormView control bound to an ObjectDataSource control (see Figure 18.2)
Trang 8FIGURE 18.1 Adding a Web Reference in Visual Web Developer
FIGURE 18.2 Retrieving the time from a web service
Trang 9LISTING 18.10 ShowWebService.aspx
<%@ Page Language=”C#” %>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<style type=”text/css”>
html
{
background-color:silver;
}
.serverTime
{
background-color:white;
font:16px Georgia,Serif;
}
.serverTime td
{
padding:40px;
}
</style>
<title>Show Web Service</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:FormView
id=”frmServerTime”
DataSourceID=”srcServerTime”
CssClass=”serverTime”
Runat=”server”>
<ItemTemplate>
The remote server date and time is: <%# Container.DataItem %>
</ItemTemplate>
</asp:FormView>
<asp:ObjectDataSource
id=”srcServerTime”
TypeName=”LocalServices.TimeService”
SelectMethod=”GetServerTime”
Runat=”server” />
</div>
</form>
</body>
</html>
Trang 10The ObjectDataSource control’s TypeName property contains both the namespace and
name of the web service proxy class (the web reference) In other words, it contains the
fully qualified name of the proxy class The SelectMethod property contains the name of
the web method represented by the proxy class
NOTE
If you open the ShowWebService.aspx page from the book’s website, you receive an
error Before the page will work correctly, you need to update the web configuration file
with the correct path to the web service on your computer
Control
You can use parameters when calling a method with the ObjectDataSource control The
ObjectDataSource control includes five parameter collections:
SelectParameters—Collection of parameters passed to the method represented by
the SelectMethod property
InsertParameters—Collection of parameters passed to the method represented by
the InsertMethod property
UpdateParameters—Collection of parameters passed to the method represented by
the UpdateMethod property
DeleteParameters—Collection of parameters passed to the method represented by
the DeleteParameters property
FilterParameters—Collection of parameters used by the FilterExpression property
DataBound controls—such as the GridView, DetailsView, and FormView controls—can
build the necessary parameter collections for you automatically
For example, the component in Listing 18.11 enables you to select movies and update a
particular movie in the Movies database table The UpdateMovie() method has four
parameters: id, title, director, and dateReleased
LISTING 18.11 Movies.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public class Movies
{