Representing Objects with the ObjectDataSource Control


Representing Objects with the ObjectDataSource Control

The 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 the .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, and web services.

Note

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).


Binding to a Component

Let's start with a really simple component. The component in Listing 15.1 is named MovieCollection. It contains one method named GetMovies(), which returns a collection of movie titles.

Listing 15.1. MovieCollection.vb

Imports System Imports System.Web.Configuration Imports System.Collections.Generic Public Class MovieCollection     Public Function GetMovies() As List(Of String)         Dim movies As New List(Of String)()         movies.Add("Star Wars")         movies.Add("Independence Day")         movies.Add("War of the Worlds")         Return movies     End Function  End Class 

You can use the page in Listing 15.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 15.2. ShowMovieCollection.aspx

<%@ Page Language="VB" %> <!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  runat="server">     <title>Show Movie Collection</title> </head> <body>     <form  runat="server">     <div>     <asp:GridView                  DataSource         Runat="server" />     <asp:ObjectDataSource                  TypeName="MovieCollection"         SelectMethod="GetMovies"         Runat="server" />     </div>     </form> </body> </html> 

In Listing 15.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.

Notice that the GridView control is bound to the ObjectDataSource control through its DataSourceID property. When you open the page in Listing 15.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 is finished 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 the next chapter, "Building Data Access Components."


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, then you should use a DataReader object.

For example, the component in Listing 15.3, the MovieDataReader component, returns all the movies from the Movies database table by using the SqlDataReader object. Notice that the component imports the System.Data.SqlClient namespace to use this Microsoft SQL Serverspecific ADO.NET object.

Listing 15.3. MovieDataReader.vb

Imports System Imports System.Data Imports System.Data.SqlClient Imports System.Web.Configuration Public Class MovieDataReader     Private ReadOnly _conString As String     Public Function GetMovies() As SqlDataReader         ' Create Connection         Dim con As New SqlConnection(_conString)         ' Create Command         Dim cmd As New SqlCommand()         cmd.Connection = con         cmd.CommandText = "SELECT Id,Title,Director FROM Movies"         ' Return DataReader         con.Open()         Return cmd.ExecuteReader(CommandBehavior.CloseConnection)     End Function     Public Sub New()         _conString = WebConfigurationManager.ConnectionStrings("Movies").ConnectionString     End Sub  End Class 

The component in Listing 15.3 actually uses three ADO.NET objects: the Connection, Command, and DataReader object. 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.

Notice that the WebConfigurationManager class is used to retrieve 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 15.4 represents the MovieDataReader object. It binds the movies to a GridView control.

Listing 15.4. ShowMovieDataReader.aspx

<%@ Page Language="VB" %> <!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  runat="server">     <title>Show Movie DataReader</title> </head> <body>     <form  runat="server">     <div>     <asp:GridView                  DataSource         Runat="server" />     <asp:ObjectDataSource                  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 15.5 returns all the records from the Movies database table. However, it uses a DataSet instead of a DataReader object.

Listing 15.5. MovieDataSet.vb

Imports System Imports System.Data Imports System.Data.SqlClient Imports System.Web.Configuration Public Class MovieDataSet     Private ReadOnly _conString As String     Public Function GetMovies() As DataSet         ' Create DataAdapter         Dim commandText As String = "SELECT Id,Title,Director FROM Movies"         Dim dad As New SqlDataAdapter(commandText, _conString)         ' Return DataSet         Dim dstMovies As New DataSet()         Using dad             dad.Fill(dstMovies)         End Using         Return dstMovies     End Function     Public Sub New()         _conString = WebConfigurationManager.ConnectionStrings("Movies").ConnectionString     End Sub  End Class 

The component in Listing 15.5 uses two ADO.NET objects: a DataAdapter and a DataSet. The SqlDataAdapter is used to represent the SQL select command, and it populates the DataSet with the results of executing the command. Notice that the WebConfigurationManager class is used to read the database connection string from the web configuration file.

The page in Listing 15.6 binds the list of movies to a DropDownList control.

Listing 15.6. ShowMovieDataSet.aspx

<%@ Page Language="VB" %> <!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  runat="server">     <title>Show Movie DataSet</title> </head> <body>     <form  runat="server">     <div>     <asp:GridView                  DataSource         Runat="server" />     <asp:ObjectDataSource                  TypeName="MovieDataReader"         SelectMethod="GetMovies"         Runat="server" />     </div>     </form> </body> </html> 

Binding to a Web Service

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 15.7 contains a simple web service that returns the current server time. You can create this file in Visual Web Developer by selecting the menu option Website, Add New Item, and selecting the Web Service item.

Listing 15.7. TimeService.asmx

<%@ WebService Language="VB"  %> Imports System Imports System.Web Imports System.Web.Services Imports System.Web.Services.Protocols <WebService(Namespace:="http://tempuri.org/")> _ <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ Public Class TimeService     Inherits System.Web.Services.WebService     <WebMethod()> _     Public Function GetServerTime() As DateTime         Return DateTime.Now     End Function  End Class 

After you create the web service in Listing 15.7, 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 are using Visual Web Developer, select the menu option 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 15.1).

Figure 15.1. Adding a Web Reference in Visual Web Developer.


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 15.8 displays the server time using a FormView control bound to an ObjectDataSource control (see Figure 15.2).

Figure 15.2. Retrieving the time from a web service.


Listing 15.8. ShowWebService.aspx

<%@ Page Language="VB" %> <html xmlns="http://www.w3.org/1999/xhtml" > <head  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  runat="server">     <div>     <asp:FormView                  DataSource         Css         Runat="server">         <ItemTemplate>         The remote server date and time is: <%# Container.DataItem %>         </ItemTemplate>     </asp:FormView>     <asp:ObjectDataSource                  TypeName="LocalServices.TimeService"         SelectMethod="GetServerTime"         Runat="server" />     </div>     </form> </body> </html> 

Notice that 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.

Note

If you open the ShowWebService.aspx page from the CD that accompanies this book, 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.





ASP. NET 2.0 Unleashed
ASP.NET 2.0 Unleashed
ISBN: 0672328232
EAN: 2147483647
Year: 2006
Pages: 276

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net