• Representing Objects with the ObjectDataSource
Control
• Using Parameters with the ObjectDataSource
Control
• Paging, Sorting, and Filtering Data with the ObjectDataSource
Control
• Handling ObjectDataSource
Control Events
• Concurrency and the ObjectDataSource
Control
• Extending the ObjectDataSource
Control
• Summary
The ObjectDataSource
control enables you to bind DataBound controls such as the GridView
, DetailsView
, and FormView
controls to a component. You can use the ObjectDataSource
control to easily build multitier applications with ASP.NET Framework. Unlike the SqlDataSource
control, which mixes data access logic in the User Interface layer, the ObjectDataSource
control enables you to cleanly separate your User Interface layer from your Business Logic and Data Access layers.
In this chapter, you learn how to use the ObjectDataSource
control to represent different types of objects. For example, you learn how to use the ObjectDataSource
control with components that represent database data. You also learn how to use the ObjectDataSource
control to represent different types of method parameters.
We tackle a number of advanced topics. For example, you learn how to page, sort, and filter database records represented by the ObjectDataSource
control. You learn how to page and sort through large database tables efficiently.
In the final section, you learn how to extend the ObjectDataSource
control to represent specialized data sources. You also learn how to extend the ObjectDataSource
control with custom parameters.
ObjectDataSource
ControlThe ObjectDataSource
control includes five main properties:
• TypeName
—The name of the type of object that the ObjectDataSource
control represents.
• SelectMethod
—The name of a method that the ObjectDataSource
calls when selecting data.
• UpdateMethod
—The name of a method that the ObjectDataSource
calls when updating data.
• InsertMethod
—The name of a method that the ObjectDataSource
calls when inserting data.
• DeleteMethod
—The name of a method that the ObjectDataSource
calls when deleting data.
An ObjectDataSource
control can represent any type of object in .NET Framework. This section discusses several types of objects you might want to represent. For example, you learn how to use the ObjectDataSource
control with components that represent collections, ADO.NET DataReaders, DataSets, LINQ to SQL queries, and web services.
You can use the ObjectDataSource
control to represent any object (any class that derives from the System.Object
class). If the object does not support the IEnumerable
interface, the ObjectDataSource
control automatically wraps the object in a new object that supports the IEnumerable interface. You can even represent an ASP.NET ListBox control with an ObjectDataSource
(not that a ListBox has any interesting methods).
Let’s start with a simple component. The component in Listing 18.1 is named MovieCollection
and contains one method named GetMovies()
, which returns a collection of movie titles.
Listing 18.1. MovieCollection.cs
You can use the page in Listing 18.2 to display the list of movies returned by the GetMovies()
method in a GridView
control. The page contains an ObjectDataSource
control that represents the MovieCollection
component.
Listing 18.2. ShowMovieCollection.aspx
In 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 represents 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.
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
.
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
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
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
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
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
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.
The page in Listing 18.8 contains an ObjectDataSource
that represents the Employee class.
Listing 18.8. ShowLINQ.aspx
Web services enable you to share information across the Internet. When you communicate 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.
Listing 18.9. TimeService.asmx
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).
Figure 18.1. Adding a Web Reference in Visual Web Developer.
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).
Figure 18.2. Retrieving the time from a web service.
Listing 18.10. ShowWebService.aspx
The 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.
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.
ObjectDataSource
ControlYou 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
The page in Listing 18.12 contains a GridView
and ObjectDataSource
control. The ObjectDataSource
control includes an UpdateMethod
property that points to the UpdateMovie()
method.
Listing 18.12. ShowMovies.aspx
In Listing 18.12, the GridView
automatically adds the update parameters to the ObjectDataSource
control’s UpdateParameters
collection. As an alternative, you can declare the parameters used by the ObjectDataSource
control explicitly. For example, the page in Listing 18.13 declares all the parameters passed to the UpdateMovie()
method.
Listing 18.13. ExplicitShowMovies.aspx
The ObjectDataSource
uses reflection to match its parameters against the parameters of the method that it calls. The order of the parameters does not matter, and the case of the parameters does not matter. However, the one thing that does matter is the names of the parameters.
You specify the type of a parameter with the Type
property, which represents a member of the TypeCode
enumeration. The TypeCode
enumeration represents an enumeration of common .NET Framework data types such as Int32
, Decimal
, and DateTime
. If the enumeration does not include a data type that you need, you can use the TypeCode.Object
member from the enumeration.
You can use all the same types of parameters with the ObjectDataSource
control that you can use with the SqlDataSource
control:
• Parameter
—Represents an arbitrary static value.
• ControlParameter
—Represents the value of a control or page property.
• CookieParameter
—Represents the value of a browser cookie.
• FormParameter
—Represents the value of an HTML form field.
• ProfileParameter
—Represents the value of a Profile
property.
• QueryStringParameter
—Represents the value of a query string field.
• SessionParameter
—Represents the value of an item stored in Session state.
For example, the page in Listing 18.14 contains a DropDownList
control and a GridView
control, which enables you to view movies that match a selected category (see Figure 18.3).
Figure 18.3. Displaying movies by category.
Listing 18.14. ShowMoviesByCategory.aspx
The ObjectDataSource
control in Listing 18.14 is bound to the component contained in Listing 18.15. The ObjectDataSource
control includes a SelectParameters
collection. The SelectParameters
collection contains a ControlParameter
, which represents the current value of the ddlMovieCategory DropDownList
control.
Listing 18.15. MovieCategories.cs
Passing long lists of parameters to methods can make it difficult to maintain an application. If the list of parameters changes, you need to update every method that accepts the list of parameters. Rather than pass a list of parameters to a method, you can pass a particular object. For example, you can pass a CompanyEmployee
object to a method used to update an employee, rather than a list of parameters that represent employee properties.
If you specify a value for an ObjectDataSource
control’s DataObjectTypeName
property, you can pass an object rather than a list of parameters to the methods that an ObjectDataSource
represents. In that case, the ObjectDataSource
parameters represent properties of the object.
For example, the EmployeeData
component in Listing 18.16 contains an InsertEmployee()
method for creating a new employee. This method is passed an instance of the CompanyEmployee
object that represents a particular employee. The CompanyEmployee
class also is included in Listing 18.16.
Listing 18.16. EmployeeData.cs
The page in Listing 18.17 contains a DetailsView
control and an ObjectDataSource
control. The DetailsView
control enables you to update existing employees in the Employees database table.
Listing 18.17. UpdateEmployees.aspx
The ObjectDataSource
control includes a DataObjectTypeName
property. This property contains the name of an object used with the UpdateEmployee()
method. When the UpdateEmployee()
method is called, an instance of the CompanyEmployee
component is created and passed to the method.
The DataObjectTypeName
property has an effect on only the methods represented by the InsertMethod
, UpdateMethod
, and DeleteMethod
properties. It does not have an effect on the method represented by the SelectMethod
property.
There is one important limitation when using the DataObjectTypeName
property. The object represented by this property must have a parameterless constructor. For example, you could not use the following CompanyEmployee
class with the DataObjectTypeName
property:
The problem with this class is that it initializes its FirstName
property in its constructor. Its constructor requires a firstName
parameter. Instead, you need to use a class that looks like this:
This class has a parameterless constructor. The FirstName
property is a read/write property.
If you have the need, you can get around this limitation by handling the Inserting
, Updating
, or Deleting
event. When you handle one of these events, you can pass any object that you need to a method. These events are discussed later in this chapter in the section “Handling ObjectDataSource
Events.”
ObjectDataSource
ControlThe ObjectDataSource
control provides you with two options for paging and sorting database data. You can take advantage of either user interface or data source paging and sorting. The first option is easy to configure, and the second option has much better performance. In this section, you learn how to take advantage of both options.
You also learn how to take advantage of the ObjectDataSource
control’s support for filtering. When you combine filtering with caching, you can improve the performance of your data-driven web pages dramatically.
Imagine that you want to use a GridView
control to display the results of a database query in multiple pages. The easiest way to do this is to take advantage of user interface paging.
For example, the page in Listing 18.18 uses a GridView
and ObjectDataSource
control to display the records from the Movies database table in multiple pages (see Figure 18.4).
Figure 18.4. Displaying multiple pages with user interface paging.
Listing 18.18. ShowUIPaging.aspx
The GridView
control in Listing 18.18 includes an AllowPaging
property set to the value True
. Setting this property enables user interface paging.
The ObjectDataSource
control in Listing 18.18 represents the MovieUIPaging
component in Listing 18.19. This component includes a GetMoviesDataSet()
method that returns an ADO.NET DataSet
object.
To take advantage of user interface paging, you must bind the GridView
control to the right type of data source., which includes a collection, a DataSet
, a DataTable
, and a DataView
. The right type of data source does not include, for example, a DataReader
.
Listing 18.19. MovieUIPaging.cs
User interface paging is convenient because you can enable it by setting a single property; however, there is a significant drawback to this type of paging. When user interface paging is enabled, all the movie records must be loaded into server memory. If the Movies database table contains 3 billion records, and you display 3 records a page, all 3 billion records must be loaded to display the 3 records. This places an incredible burden on both the web server and database server. In the next section, you learn how to use data source paging, which enables you to work efficiently with large sets of records.
Data source paging enables you to write custom logic for retrieving pages of database records. You can perform the paging in the component, a stored procedure, or a LINQ to SQL query.
If you want the best performance, you should write your paging logic in either a stored procedure or a LINQ query. We examine both approaches in this section.
The page in Listing 18.20 contains an ObjectDataSource
control with data source paging enabled.
Listing 18.20. ShowDSPaging.aspx
The ObjectDataSource
control includes an EnablePaging
property that has the value True
. The ObjectDataSource
also includes a SelectCountMethod
property that represents the name of a method that retrieves a record count from the data source.
Furthermore, that the GridView
control includes both an AllowPaging
and PageSize
property. Even when using data source paging, you need to enable the AllowPaging
property for the GridView
so that the GridView
can render its paging user interface.
When an ObjectDataSource
control has its EnablePaging
property set to the value True
, the ObjectDataSource
passes additional parameters when calling the method represented by its SelectMethod
property. The two additional parameters are named StartRowIndex
and MaximumRows
.
Now that we have the page setup for data source paging, we need to create the component. Let’s start by using a LINQ to SQL query. This approach is the easiest and recommended way. The component in Listing 18.21 uses LINQ to SQL queries to implement both the GetMovies()
and GetMovieCount()
methods.
Listing 18.21. MoviesLINQPaging.cs
Before you can use the component in Listing 18.21, you need to create a DataContext
named MyDatabaseDataContext
. You can create this DataContext
by selecting Website, Add New Item, and adding a new LINQ to SQL Classes item to your website. Name the new LINQ to SQL Classes item MyDatabase.dbml
. Next, after the LINQ to SQL Designer opens, drag the Movies database table from the Database Explorer window onto the Designer surface.
Unfortunately, when you drag the Movies database table onto the LINQ to SQL Designer surface, the Designer may create a new entity named Movy. The Designer is attempting to singularize the word and it fails badly. You must rename the entity to Movie in the Properties window.
You are not required to use LINQ to SQL when you want to implement data source paging. As an alternative to LINQ to SQL, you can perform your paging logic within a SQL stored procedure. The component in Listing 18.22 contains ADO.NET code instead of LINQ to SQL queries.
Listing 18.22. MoviesSQLPaging.cs
To improve performance, the GetMovieCount()
method attempts to retrieve the total count of movie records from the server cache. If the record count cannot be retrieved from the cache, the count is retrieved from the database.
The GetMovies()
method calls a stored procedure named GetPagedMovies
to retrieve a particular page of movies. The StartRowIndex
and MaximumRows
parameters are passed to the stored procedure. The GetPagedMovies
stored procedure is contained in Listing 18.23.
Listing 18.23. GetPagedMovies.sql
The GetPagedMovies
stored procedure returns a particular page of database records. The stored procedure creates a temporary table named #PageIndex that contains two columns: an identity column and a column that contains the primary key values from the Movies database table. The temporary table fills in any holes in the primary key column that might result from deleting records.
Next, the stored procedure retrieves a certain range of records from the #PageIndex table and joins the results with the Movies database table. The end result is that only a single page of database records is returned.
When you open the page in Listing 18.20, the GridView
displays its paging interface, which you can use to navigate between different pages of records (see Figure 18.5).
Figure 18.5. Displaying multiple pages with data source paging.
The paging mechanism described in this section is based on the mechanism used by the Microsoft ASP.NET forums at http://www.asp.net/forums and the XBOX forums at http://www.xbox.com. Both of these websites handle an incredible number of message posts every day. The forums software was written with ASP.NET and is available from TelligentSystems (www.telligentsystems.com) as part of their Community Server product.
If temporary tables make you anxious, you have an alternative when working with Microsoft SQL Server 2005 or 2008. You can take advantage of the new ROW_NUMBER()
function to select a range of rows. The ROW_NUMBER()
function automatically calculates the sequential number of a row within a resultset.
The modified stored procedure in Listing 18.24 does the same thing as the stored procedure in Listing 18.23. However, the modified stored procedure avoids any temporary tables.
Listing 18.24. GetPagedMovies2005.sql
If you need to sort the records displayed by the GridView
control, the easiest type of sorting to enable is user interface sorting. When you take advantage of user interface sorting, the records are sorted in the server’s memory.
For example, the page in Listing 18.25 contains a GridView
that has its AllowSorting
property set to the value True
. The GridView
is bound to an ObjectDataSource
that represents the Employees database table (see Figure 18.6).
Figure 18.6. Sorting records with user interface sorting.
Listing 18.25. ShowUISorting.aspx
The ObjectDataSource
control in Listing 18.25 is bound to the component in Listing 18.26. The GetEmployees()
method returns an ADO.NET DataSet
object. When taking advantage of user interface sorting, the ObjectDataSource
control must represent the right type of data source. The right type of data source includes DataSet
, DataTable
, and DataView
controls.
Listing 18.26. EmployeesUISorting.cs
User interface sorting is convenient. You can enable this type of sorting by setting a single property of the GridView
control. Unfortunately, just as with user interface paging, some serious performance drawbacks result from user interface sorting. All the records from the underlying database must be loaded and sorted in memory. This is a particular problem when you want to enable both sorting and paging at the same time. In the next section, you learn how to implement data source sorting, which avoids this performance issue.
Imagine that you are working with a database table that contains 3 billion records and you want to enable users to both sort the records and page through the records contained in this table. In that case, you want to implement both data source sorting and paging.
The page in Listing 18.27 contains a GridView
and ObjectDataSource
control. The GridView
has both its AllowSorting
and AllowPaging
properties enabled (see Figure 18.7).
Figure 18.7. Paging and sorting database records.
Listing 18.27. ShowDSSorting.aspx
The ObjectDataSource
control in Listing 18.27 represents the EmployeesDSSorting
component in Listing 18.28. The ObjectDataSource
control includes a SortParameterName
property. When this property is present, the ObjectDataSource
control uses data source sorting instead of user interface sorting.
Listing 18.28. EmployeesDSSorting.vb
The GetEmployees()
method in the component in Listing 18.28 calls a stored procedure to sort and page records. The stored procedure, named GetSortedEmployees
, returns a sorted page of records from the Employees database table. This stored procedure is contained in Listing 18.29.
Listing 18.29. GetSortedEmployees.sql
The stored procedure in Listing 18.29 uses SQL CASE
functions to sort the records before they are added to the temporary table. Unfortunately, you can’t use a parameter with an ORDER BY
clause, so the sort columns must be hard-coded in the CASE
functions. Next, a page of records is selected from the temporary table.
As an alternative to the data source sorting method described in this section, you can use LINQ to SQL. For more information on LINQ to SQL, see Chapter 20.
You can supply the ObjectDataSource
control with a filter expression. The filter expression is applied to the data returned by the control’s select
method. A filter is particularly useful when used in combination with caching. You can load all the data into the cache and then apply different filters to the cached data.
You learn how to cache data with the ObjectDataSource
control in Chapter 29, “Caching Application Pages and Data.”
For example, the page in Listing 18.30 contains a DropDownList
and GridView
control. The DropDownList
displays a list of movie categories, and the GridView
displays matching movies (see Figure 18.8).
Figure 18.8. Filtering movies with the ObjectDataSource
control.
Listing 18.30. ShowFilteredMovies.aspx
Both ObjectDataSource
controls in Listing 18.30 have caching enabled. Furthermore, the second ObjectDataSource
control includes a FilterExpression
property that filters the cached data, using the selected movie category from the DropDownList
control.
Both ObjectDataSource
controls represent the component in Listing 18.31.
Listing 18.31. FilterMovies.cs
The ObjectDataSource
enables you to filter data only when the data is represented by a DataSet
, DataTable
, or DataView
object. This means that if you use filtering, the data must be returned as one of these objects.
Behind the scenes, the ObjectDataSource
control uses the DataView.RowFilter
property to filter database rows. You can find detailed documentation on proper filter syntax by looking up the DataColumn.Expression
property in the .NET Framework SDK Documentation.
ObjectDataSource
Control EventsThe ObjectDataSource
control supports the following events:
• Deleting
—Occurs immediately before the method represented by the DeleteMethod
property is called.
• Deleted
—Occurs immediately after the method represented by the DeleteMethod
property is called.
• Inserting
—Occurs immediately before the method represented by the InsertMethod
property is called.
• Inserted
—Occurs immediately after the method represented by the InsertMethod
property is called.
• Selecting
—Occurs immediately before the method represented by the SelectMethod
property is called.
• Selected
—Occurs immediately after the method represented by the InsertMethod
property is called.
• Updating
—Occurs immediately before the method represented by the InsertMethod
property is called.
• Updated
—Occurs immediately after the method represented by the InsertMethod
property is called.
• Filtering
—Occurs immediately before the filter expression is evaluated.
• ObjectCreating
—Occurs immediately before the object represented by the ObjectDataSource
control is created.
• ObjectCreated
—Occurs immediately after the object represented by the ObjectDataSource
control is created.
• ObjectDisposing
—Occurs before the object represented by the ObjectDataSource
control is destroyed.
Most of these events come in pairs. One event happens immediately before a method is called, and one event happens immediately after a method is called. You can handle these events to modify the parameters and objects represented by an ObjectDataSource
control. You can also use these events to handle any errors that might result from calling methods with the ObjectDataSource
control.
You can handle the Selecting, Inserting, Updating, and Deleting events to modify the parameters that are passed to the methods called by the ObjectDataSource
control. There are several situations in which you might want to do this.
First, if you work with an existing component, you might need to change the names of the parameters passed to the component. For example, instead of passing a parameter named id
to an update method, you might want to rename the parameter to movieId
.
Second, you might want to pass additional parameters to the method called. For example, you might need to pass the current username, the current IP address, or the current date and time as a parameter to a method.
For example, imagine that you want to create a guestbook and automatically associate the IP address of the user making an entry with each entry in the guestbook. The page in Listing 18.32 illustrates how you can do this with the help of a FormView
control and an ObjectDataSource
control (see Figure 18.9).
Figure 18.9. Displaying a guestbook.
Listing 18.32. ShowGuestbook.aspx
The page in Listing 18.32 includes an Inserting event handler. When the insert method is called, the IP address of the current user is added to the parameters collection.
The ObjectDataSource
control in Listing 18.32 is bound to the Guestbook
component in Listing 18.33.
Listing 18.33. Guestbook.cs
Realize that you can manipulate the parameters collection in any way that you need. You can change the names, types, or values of any of the parameters.
You can handle the Selected
, Inserted
, Updated
, or Deleted
events to handle any errors that might result from calling a method. For example, the page in Listing 18.34 handles the Inserting
event to capture any errors raised when the method represented by the ObjectDataSource
control’s InsertMethod
property is called.
Listing 18.34. HandleErrors.aspx
In Listing 18.34, the Inserted
event handler checks for an exception. If an exception exists, the exception is handled and an error message displays (see Figure 18.10).
Figure 18.10. Handling method errors gracefully.
The page in Listing 18.34 is bound to the component in Listing 18.35.
Listing 18.35. InsertMovie.cs
You can create an exception by entering a new movie record and not supplying a value for one of the fields. For example, the Title column in the Movies database table does not accept null values.
Instead of handling errors at the level of the DataSource control, you can handle errors at the level of the DataBound
control. For example, the DetailsView
control supports an ItemInserted
event.
ObjectCreating
EventBy default, the ObjectDataSource
control can represent only components that have a constructor that does not require any parameters. If you are forced to use a component that does require parameters for its constructor, you can handle the ObjectDataSource
control’s ObjectCreating
event.
For example, the component in Listing 18.36 must be initialized with a movie category parameter. The component returns only movies in the specified category.
Listing 18.36. MoviesByCategory.cs
The page in Listing 18.37 contains an ObjectDataSource
control that represents the MoviesByCategory
component. The page includes a handler for the ObjectCreating
event so that it can assign an initialized instance of the MoviesByCategory
component to the ObjectDataSource
control.
Listing 18.37. ShowAdventureMovies.aspx
Even though the MoviesByCategory
component is initialized in the ObjectCreating
event handler, you still must assign the name of the component to the ObjectDataSource
control’s TypeName
property. The ObjectDataSource
control needs to know what type of object it is representing when it calls its methods.
ObjectDataSource
ControlImagine that two users open the same page for editing the records in the movies database table at the same time. By default, if the first user submits changes before the second user, the first user’s changes are overwritten. In other words, the last user to submit changes wins.
This default behavior of the ObjectDataSource
control can be problematic in an environment in which a lot of users work with the same set of data. You can modify this default behavior by modifying the ObjectDataSource
control’s ConflictDetection
property. This property accepts the following two values:
• CompareAllValues
—Causes the ObjectDataSource
control to track both the original and new values of its parameters.
• OverwriteChanges
—Causes the ObjectDataSource
to overwrite the original values of its parameters with new values (the default value).
When you set the ConflictDetection
property to the value CompareAllValues
, you should add an OldValuesParameterFormatString
property to the ObjectDataSource
control. You use this property to indicate how the original values the database columns should be named.
The page in Listing 18.38 contains a GridView
and ObjectDataSource
control, which you can use to edit the movies in the Movies database table. The ObjectDataSource
control includes a ConflictDetection
property with the value CompareAllValues
and an OldValuesParameterFormatString
property with the value original_{0}
.
Listing 18.38. ShowConflictDetection.aspx
The ObjectDataSource
control in Listing 18.38 is bound to the component in Listing 18.39.
Listing 18.39. ConflictedMovies.cs
The component in Listing 18.39 includes an UpdateMovie()
method. This method accepts five parameters: original_title
, title
, original_director
, director
, and original_id
.
The UpdateMovie()
method raises an exception when the original parameter values don’t match the current values in the Movies database table. The command executed by the Command
object looks like this:
This statement updates a row in the database only when the current values from the row match the original values selected from the row. If the original and current values don’t match, no records are affected and the UpdateMovie()
method raises an exception.
ObjectDataSource
ControlIn this final section, we examine two methods of extending the ObjectDataSource
control. You learn how to create a custom data source control by deriving a new control from the ObjectDataSource
control. You also learn how to create custom parameters that can be used with the ObjectDataSource
and other DataSource
controls.
ObjectDataSource
ControlIf you discover that you are declaring an ObjectDataSource
control with the same properties on multiple pages, it makes sense to derive a new control from the ObjectDataSource
control that has these properties by default. That way, you can simply declare the derived control in a page.
For example, if you display a list of movies in multiple pages in your website, it would make sense to create a specialized MovieDataSource
control.
The control in Listing 18.40, named the MovieDataSource
control, derives from the base ObjectDataSource
control class. The MovieDataSource
control represents the MoviesComponent
, which is also contained in Listing 18.40.
Listing 18.40. MovieDataSource.cs
The MovieDataSource
control initializes the base ObjectDataSource
control’s TypeName
and SelectMethod
properties in its constructor. The TypeName
is assigned the fully qualified name of the MoviesComponent
.
The page in Listing 18.41 illustrates how you can use the MovieDataSource
control in a page (see Figure 18.11).
Figure 18.11. Using the MovieDataSource
control to display movies.
Listing 18.41. ShowMovieDataSource.aspx
The custom control must be registered with a <%@ Register %>
directive at the top of Listing 18.41. After you register the control, you can simply declare the MovieDataSource
control in the page to represent the contents of the Movies database table.
As an alternative to registering the MovieDataSource
control in a page, you can register the control for an entire application in the web configuration file within the <pages>
element.
The standard DataSource Parameter objects included in the ASP.NET Framework enable you to represent objects such as query string values, items from Session state, and the values of control properties. If none of the standard Parameter objects satisfy your requirements, you always have the option of creating a custom Parameter object.
You create a custom Parameter object by deriving a new class from the base Parameter
class. In this section, we create two custom parameters. The first is a UsernameParameter
that automatically represents the current username. Next is a PagePropertyParameter
that represents the current value of a property contained in the page.
The UsernameParameter
class is contained in Listing 18.42. The class in Listing 18.42 derives from the Parameter class and overrides the Evaluate()
method of the base class. The Evaluate()
method determines what the parameter represents.
Listing 18.42. UsernameParameter.cs
The UsernameParameter
returns the current username. The parameter retrieves this information from the current HttpContext
passed to the Evaluate()
method. The UsernameParameter
is used in the page in Listing 18.43.
Listing 18.43. ShowUsernameParameter.aspx
The UsernameParameter
is declared in the ObjectDataSource
control’s InsertParameters
collection. When you add a new entry to the guestbook, your username is added automatically (see Figure 18.12).
Figure 18.12. Inserting records with the UsernameParameter
.
PagePropertyParameter
enables you to represent an arbitrary property of the current page. The property being represented can return whatever type of value you want. The code for the PagePropertyParameter
is contained in Listing 18.44.
Listing 18.44. PagePropertyParameter.cs
The component in Listing 18.44 overrides the Evaluate
method of the base Parameter
class. The DataBinder.Eval()
method is used to return the value of a property of the current page.
The page in Listing 18.45 uses the PagePropertyParameter
to represent a property of the page named CurrentUsername
. This property returns the current username.
Listing 18.45. ShowPagePropertyParameter.aspx
In Listing 18.45, the PagePropertyParameter
represents the current username. Because the PagePropertyParameter
can represent any page property, the parameter could represent any type of value.
In this chapter, you learned how to use the ObjectDataSource
control to represent different types of objects. In the first section, you were provided with sample code that demonstrated how you can use the ObjectDataSource
control to represent a collection, DataReader
, DataSet
, a LINQ to SQL query, and a web service.
We also discussed how you can use the ObjectDataSource
control to page, sort, and filter data. You learned how to implement both user interface paging and data source paging, which enables you to efficiently work with very large sets of records.
Next, we examined how you can handle ObjectDataSource
control events. You learned how to add and modify the parameters represented by the ObjectDataSource
control. You also learned how to gracefully handle errors raised when executing an ObjectDataSource
control method.
Finally, we discussed two methods of extending the ObjectDataSource
control. You learned how to derive a new control from the base ObjectDataSource
control to represent specialized data sources such as a Product data source. We also discussed how you can create custom Parameter
objects that can be used with the ObjectDataSource
control.