Anda di halaman 1dari 51

The Data Source Object Model

The key issue with ASP.NET data binding is a lack of a higher-level and possibly declarative model for data fetching and manipulation (edit, insert, and delete). As a result, an ASP.NET 1.x data access layer is boring to write and requires hundreds of lines of code even for relatively simple scenarios.

The ASP.NET 2.0 data source model addresses this problem. To simplify the data binding mechanism, the architecture of data-bound controls now supports a new family of data componentsthe data source componentswhich in turn support a declarative model of binding.

The data source control represents a source of data that returns and accepts data over a well-known stream such as SQL, XML, DataSet, and custom formats such as the Microsoft Excel worksheets.

The Rationale of Data Source Components

The data binding model of ASP.NET 2.0 provides two ways of connecting programmatically (as in ASP.NET 1.x) and declaratively (using data source components)

Codeless Data Binding

In ASP.NET 2.0 developers can set up sophisticated Web sites without knowing a lot of SQL or the page life cycle. Codeless data binding, and the data source model in particular, also lets developers work together, each contributing the best of his skills. ASP.NET 2.0 data binding enables page developers to implement data binding scenarios, including displaying, editing, paging, and sorting data, with no code.

ASP.NET 2.0 adds a new property to all data-bound controls so that any control can be successfully bound to a new data source control. The new property,DataSourceId, matches the name of a data source control defined in the same page. The following code snippet shows how to list the employees in the Northwind Employees database. The data-bound control used for the output is the Repeater.

<asp:SqlDataSource runat="server ID="MySource ConnectionString="SERVER=;DATA BASE=northwind;UID=; DataSourceMode="DataSet SelectCommand="SELECT firstname, lastname FROM employees />

<asp:Repeater runat="server ID="data DataSourceId="MySource > <ItemTemplate> <%# Eval(ProductName) %> <%# Eval(Price) %> <br> </ItemTempate> </asp:Repeater>

Defining a Standard Set of Data Operations

A data source component is a data control that can implement some or all of a standard set of data operations. Whether a control implements the entire standard set of operations or only a subset depends on the class. The standard set of data operations includes the four basic I/O operations: select, delete, insert, and update.

Binding Data Source Components to Controls

One difference between data source components and ASP.NET 1.x bindable classes is that the new data source object model allows you to select, insert, delete, and update data stored in a bound sourcebe it a relational database,an XML file, or an Excel document.

Data Source Control Internals

A data source control is a .NET Framework class that facilitates the binding ofdata between data stores and data-bound controlsboth existing controls such as the DataGrid and new data-bound controls such as GridView, TreeView, and DetailsView.

The DataSourceControl abstract class serves as the base class for all data source controls and defines the interface between data-bound controls and the underlying data. A data source control exposes the contents of its underlying data source through a set of properties and methods. Some of these members are specific to the control; others are common to all source controls and are defined as part of the IDataSource interface.

Tabular Data Source Controls

shows a diagram of the classes that form the data source object model.

Tabular data source controls are AccessDataSource, DataSetDataSource, Object-DataSource, and SqlDataSource.

SqlDataSource control
The SqlDataSource control is a data source control that represents a connection to a relational data store such as SQL Server or Oracle or any data source accessible through OLE DB and ODBC bridges.

You set up the connection to the data store using two main properties,ConnectionString and ProviderName. The former represents the connection string and contains enough information to open a session with the underlying engine. The latter specifies the namespace of the ADO.NET managed provider to use for the operation. The ProviderName property defaults System.Data.SqlClient, which means that the default data store is SQL Server.

The DataSourceMode property controls how the Select command retrieves data. The DataSourceMode property accepts values defined by the SqlDataSourceMode enumeration DataSet and DataReader.

Code Usage
<asp:SqlDataSource runat="server ID="MySqlSource ConnectionString="SERVER=;DATAB ASE=northwind;UID=; SelectCommand="SELECT * FROM employees />

The AccessDataSource Class

The AccessDataSource control is a data source control that represents a connection to an Access database. In particular, the AccessDataSource control replaces properties such as ConnectionString and ProviderName with a more direct DataFile property. You set this property to the .mdb database file of choice. The data source control resolves the file path at run time and uses the Microsoft Jet 4 OLE DB provider to connect to the database.

Code Usage
The following code shows how to use the AccessDataSource control to open an .mdb file and bind its content to a drop-down list control. <asp:AccessDataSource runat="server ID="MyAccessSource DataFile="nwind.mdb" SelectCommand="SELECT * FROM Customers /> Select a Customer: <asp:DropDownList runat="server DataSourceId="MyAccessSource />

Several features of the AccessDataSource control are inherited from the base class, SqlDataSource. In fact, the Access data source control is basically a SQL data source control optimized to work with Access databases. The ShareMode property controls how the Access data source opens thedatabase and determines what data operations can be performed. The defaultvalue is Read, which means that only the Select operation can be accomplished

In read mode, the CanDelete, CanInsert, and CanUpdate properties all return false, thus blocking the corresponding data operations. To enable read/write operations, set ShareMode to ReadWrite.

The DataSetDataSource Class

The DataSetDataSource class takes an XML file or static data (such as an XML string) as input and exposes the DataSet representation of this data to databound controls. The DataSetDataSource class instantiates a DataSet object and uses the DataSet objects ReadXml method to parse the XML input. Ideally, the supplied XML data is a DiffGram script or any XML file created by the DataSets WriteXml method.

Code Usage
<asp:GridView runat="server ID="grid DataSourceId="MyDataSetSource AutoGenerateColumns="true"> </asp:GridView> <asp:DataSetDataSource runat="server ID="MyDataSetSource DataFile="data.xml />

The ObjectDataSource Class

The ObjectDataSource class enables business components to associate their contents to databound controls. The class supports declarative parameters that allow developers to pass pagelevel variables to the objects methods. The ObjectDataSource control is designed to simplify and encourage a common practice among page developersencapsulating data retrieval and business logic into an additional layer between the presentation page and data provider.

The SiteMapDataSource Class

A site map is a graph that represents all the pages and directories found in a Web site. Site map information is used to show users the logical coordinates of the page they are visiting,allow them to access site locations dynamically, and render all the navigation information in a graphical fashion. The site map is a hierarchical piece of information that can be used as input for a hierarchical data source control. This control is the SiteMapDataSource class.

ASP.NET 2.0 provides richer support for site maps. You start by creating a configuration file named app.sitemap in the root of the Web application. The file describes the relationship between pages on the site.

The XmlDataSource Class

The XmlDataSource control is a special type of data source control that supports both tabular and hierarchical views of data. The tabular view of XML data is just a list of nodes at a given level of hierarchy, whereas the hierarchical view shows the complete hierarchy.

An XML node is an instance of the XmlNode class; the complete hierarchy is an instance of the XmlDocument class. The XML data source supports both read-only and read-write scenarios. The XmlDataSource control can accept XML input data as a relative or absolute filename assigned to the DataFile property or as a string containing the XML content assigned to the Data property.

The control exposes that data through the IDataSource or the IHierarchicalDataSource interface. In general, the XmlDataSource control is commonly bound to a hierarchical control, such as the TreeView.

Code Usdage(1)
To understand how the XML data source works, consider the following small XML file, named data.xml:

<warehouse> <department name="dairy deptid="111"> <category name="yogurt categoryid="2222"> <product name="horizon sku="3333-3333"/> </category> </department> </warehouse>

Code Usage(2)
<asp:XmlDataSource runat="server ID="MyXmlSource DataFile="data.xml /> <asp:TreeView runat="server DataSourceId="MyXmlSource"> <DataBindings> <asp:TreeNodeBinding Depth="0 DataMember="Department TextField="Name ValueField="DeptId /> <asp:TreeNodeBinding Depth="1 DataMember="Category TextField="Name ValueField="CategoryId /> <asp:TreeNodeBinding Depth="2 DataMember="Product TextField="Name ValueField="SKU /> </DataBindings> </asp:TreeView>

The Final Result

Using the SqlDataSource Control

The SqlDataSource control represents a connection to an ADO.NET managed data provider, such as SQL Server, OLEDB, ODBC, Oracle, or a third-party provider.

Data Source Parameters

In the programming interface of the SqlDataSource control each command property has its own collection of parameters. A parameter collection is a collection class named ParameterCollection.

It stores objects whose base class is Parameter. The Parameter class represents a parameter in a parameterized query, filter expression, or command executed by a data source control.

Code Usage(1)
<asp:SqlDataSource runat="server ID="MySource ConnectionString="SERVER=;DATAB ASE=northwind;UID=;" DataSourceMode="DataSet SelectCommand="SELECT firstname, lastname FROM employees WHERE employeeid > @MinID">

Code Usage(2)
<SelectParameters> <asp:ControlParameter Name="MinID ControlId="EmpID PropertyName="Text /> </SelectParameters> </asp:SqlDataSource>

The query contains a placeholder named @MinID. The data source control automatically populates the placeholder with the information returned by the ControlParameter objectone of the supported parameter types in ASP.NET 2.0. The

Parameter Types
How a parameter is bound to a value depends on the type of the parameter.

Parameter Types in ASP.NET 2.0

Parameter Description ControlParameter: Gets the parameter value from any public property of a server control. CookieParameter: Sets the parameter value based on the content of the specified HTTP cookie. FormParameter: Gets the parameter value from the specified input field in the HTTP request form.

ProfileParameter: Gets the parameter value from the specified property name in the profile object created from the applications personalization scheme.

QueryStringParameter: Gets the parameter value from the specified variable in the request query string. SessionParameter: Sets the parameter value based on the content of the specified Session slot.

Each parameter class has a Name property and a set of properties specific to its role and implementation.

Caching Behavior
Data caching is crucial to any realistic Web application and an important feature to optimize to make the application run faster. Caching is also an important aspect of data source controls. A data source control retrieves data that will be made available to other components within the application. When multiple pages need to access this information, an up-to-date cache provides for a significantly faster response.

You can instruct the SqlDataSource control to cache the results of a query for a certain amount of timebut only if the data source mode is DataSet. The Sql-DataSource control provides automatic caching using a time-based cache expiration policy. It can also support an expiration policy based on the new SqlCacheDependency component.

Enabling Automatic Caching

To enable caching on the data sourcecaching is disabled by defaultyou set the EnableCaching property to true. You should also give the CacheDuration property a nonzero value.

The CacheDuration property specifies the number of seconds before the contents of the data source are discarded, to be reloaded on the next request.

<asp:SqlDataSource runat="server ConnectionString="DSN=MyData" ProviderName="System.Data.Odbc" SelectCommand="SELECT * FROM products" EnableCaching="true" CacheDuration="3600 />

SQL Server Cache Dependency

The SqlDataSource control also supports a form of cache expiration based on a dependency between its contents and a table in a SQL Server database. The dependency is specified as a string property. The syntax has the form database:table. The database part of the string must refer to a database listed under the <sqlCacheDependency> section of the web.config file,and the table part must be the name of a table in that database. You can specify multiple table dependencies by separating them with semicolons

<asp:SqlDataSource runat="server ConnectionString="SERVER=;DATABASE=p ubs;UID=;" SelectCommand="sp_getdata" EnableCaching="true" CacheDuration="3600 SqlCacheDependency="pubs:Authors;pubs:TitleA uthor />