ASP.NET Data Source Object Model
In this tutorial you will learn about Data Source Object Model in ASP.NET 2.0, the Rationale of DataSource components, Data Source Control Internals, Tabular DataSource Controls, Hierarchical Data Source Controls, The SqlDataSource Control: Usage and Data Source Parameters.
The Rationale of DataSource components
The ASP.NET 2.0 data source model provides support for a declarative model of data binding. The data source components return and accept data from familiar streams such as SQL, XML, DataSet and from custom formats too. The schema is very approachable, time saving and simplifies the binding mechanism.
The codeless data binding environment of ASP.NET 2.0 does not require the developer to know any SQL or about page life cycles. The glue code is automatically provided by the plumbing of the control and developers can implement data binding scenarios such as display, edit, page and sort functionalities with no code. This model has a lot of similarity with the
The ASP.NET 2.0 code is declarative. It sets up a connection, handles possible parameters, executes the statements and caches the final subset. Everything is tightly integrated with the existing framework of server controls and new properties are added to all the data-bound controls so that every control can be successfully bound to the data source. For instance the DataSourceId is a new property that matches the name of the data source control defined and can list the data from the data source using another control called the Repeater. The code also shows a more compact syntax for binding data.
Data can be bound to a data control using the DataSource Property or the DataSourceId property. Both are mutually exclusive and an exception would be thrown if both are set together. We will be exploring this in greater detail a little later in this lesson and in the next lesson of this series.
As stated earlier, a variety of data sources including custom data sources, are supported using a single model. The component can implement some or all of a standard set of data operations—such as select, insert, Update and Delete. The class determines the operations that will be implemented by the Data control.
The data control fetches and returns the data as an object and the type returned depends on the particular kind of implementation supported and the data can be sorted and filtered if the same is supported. Page developers can use these operations using a number of intuitive method calls on the data source control object. The methods are categorized in the new interface that is peculiar to the control being used.
The data source model is not an alternative to ADO.NET or OLE DB. It forms a layer of code that interfaces between data bound controls and low level API that is used to retrieve data. The low level API can be ADO.NET, System.Xml, or Microsoft Indexing Service or an Excel COM object model. The data, in other words, can be retrieved from any kind of data source irrespective of the kind of data source control used.
At design time the developer has a richer experience in that the simplified set of advanced controls performs I/O operations on generic blocks of data. This speeds up development times and makes page composition easier and simpler. This also ensures that all data access scenarios can be implemented with least amount of code. Additionally designers can work with real time data and consequently give the interface a reasonable schema.
Data Source Control Internals
The purpose of the data source control is that it binds the data control and the data store. A data source control represents one or more named views of data and provides an enumeration of data objects. The data source can be managed using SQL Statements such as SELECT, INSERT, UPDATE and DELETE. The Data source control inherits from the base class Control which can be tabular or hierarchical. The DataSourceControl abstract class serves as the base class for all data source controls and defines the interface between data bound controls and underlying data. This control is not visually rendered but has a declarative persistence as part of the .aspx source code and gives access to the page’s view state.
As repeatedly stated, the data source control exposes the contents of its underlying data source through a set of properties and methods. A number of methods which are common to all the controls are implemented by the IDatasource Interface. This is the base interface for creation of custom controls. It has one event and a few methods only. The DataSourceChanged event requires delegates with the default prototype called EventHandler class. This event is fired whenever there is a change in the data source and it impacts the control that is bound to it. The GetView method collects the name of the data source view to retrieve and return it as a DataSourceView object. The GetViewNames returns a collection of names representing the list of view objects associated with the current instance of the data source control. The DataSourceControl base class does not permit addition of any extra properties or methods.
A data source view architecture looks like a collection of named views. It provides a customized view of data with special settings for viewing, sorting, filtering and other data operations. It is inherited from the DataSourceView class and is associated within the data view control. The CanDelete defines whether deletions are permitted on the underlying data source. CanInsert, defines whether permission to insert into the data source exists. CanPage indicates whether paging can be done on the view. CanSort defines sorting permission for the data view. CanretrieveTotalRowCount indicates whether information about total row count is available. CanUpdate indicates whether update on the data source is allowed. Name returns the name of the current view. The methods in the DataSourceView are Delete, Insert, Select and Update.
Tabular DataSource Controls
The Data source Control can be a tabular control or a hierarchical control. The four data source controls that express data in a tabular form are AccessDataSource, DataSetDataSource, ObjectDataSource and SqlDataSource.
AccessDataSource control represents a connection to an Access Database. It inherits from the SqlDataSource control and does not accept the connectionString and ProviderName properties. The DataFile property will have to be set to point to the actual MDB file. The Jet 4.0 OLE DB provider is used to connect to the database.
The DataSetDataSource works with an XML data source object. It can be specified as a string or a filename. This control cannot be bound to a DataSet object. The methods of the class are used to retrieve the DataSet object and set schema information. Though it is XML based, it only supports tabular representation of data and can be bound only to list controls. These controls are used only in read only scenarios. However, the control supports editing of underlying XML data.
The ObjectDataSource supports custom binding. This class is specified using the TypeName property of a control. It allows developers to structure applications using three tier architecture and still take advantage of the ASP.NET 2.0 declarative data binding model. It follows specific design patterns and includes parameterless constructors and methods that behave in familiar ways.
The SqlDataSource is a connection to an ADO.NET data provider and returns a SQL data. It includes data sources accessible through OLE DB and ODBC. The connection string and provider name can be specified through properties of this class.
Hierarchical Data Source Controls
As the name suggests these controls allow the representation of data hierarchies. It derives from the abstract class HierarchicalDataSourceControl class which implements the IHierarchicalDataSource Interface. It has a single method called the GetHierarchicalView. This method retrieves hierarchical data source view and returns the object of the type after taking the path of the view. Each level of data is supported by a view. The ViewPath parameter indicated the path in the hierarchy for navigation and retrieval of the requested data. Though conceptually the same, tabular and hierarchical views, are different in so far as the data they handle are different. The SiteMapDataSource and the XmlDataSource are two hierarchical data source controls supported by ASP.NET 2.0.
The SiteMapDataSource control has a rich navigation infrastructure that allows developers to specify the site structure. The control is the SiteMapDataSource class and connects to an XML data source. A configuration file named app.sitemap created at the root of the application is referred to at runtime. It creates a relationship between the pages of the site. A control named NavigationPath is added to the pages and this control retrieves the site map and produces the necessary markup. We shall study this control in greater detail in the next lesson of this series. This class has a few properties that relate to the site map provider. SiteMapProvider specifies the name of the site map provider. The SiteMapViewtype describes the type of view that has to be generated by the control. The StartingNodeType, StartingNodeUrl and StartingDepth are properties that indicate the node with which to start, its address and the depth to which the hierarchy needs to be displayed.
The XmlDataSource control is a special control that supports both tabular and hierarchical views of data. The tabular version displays the data as a list of nodes at a specified level of hierarchy, while the hierarchical view shows the complete hierarchy. This control can accept XML input data as relative or an absolute filename assigned to the Datafile property or to a string containing the XML content assigned to the Data property. It can also be passed in as a SchemaFile or Schema string. The control exposes the data for the XML data source through the IDataSource or the IHierarchicalDataSource interface. It is normally bound to a hierarchical control such as TreeView. The class can also transform its data using Extensible StyleSheet language transformation(XSLT). The transform file can be set using the TransformFile property or assigning a string property named Transform. The TransformArgumentList property passes arguments to the style sheet using the XSL Transformation. Once the data is transformed the XmlDataSource property becomes read only.
The SqlDataSource Control: Usage
The SqlDataSource control defines a connection between the ADO.NET managed data provider –Sql Server, OLE DB, ODBC, Oracle or a third party provider. Commands to perform common data operations such as query or sort can be specified. The text assigned to InsertCommand or SelectCommand can be parsed to verify whether it is a valid SQL command that is compliant with the expected syntax of the corresponding statement. By default the command text is taken as the name of the stored procedure. The binding between the data provider and the user code takes place codelessly or declaratively. It can also be invoked programmatically. It incorporates a number of functions and features and can accept parameters in both stored procedures and in SQL Commands.
Data Source Parameters
The parameter collection is defined in the collection class name ParameterCollection. All objects whose base class is Parameter can be stored in this collection. Parameterized query, filter expressions, or commands executed by the data source control are examples of Parameter objects.
Parameters can be obtained and set in several ways. ControlParameter gets the parameter value from any public property of a server control. CookieParameter sets the parameter property of the 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 from the personalization scheme of the application. 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. The Name property of the parameter class has a set of properties that specify the role and implementation of the property.
The Evaluate method of the Parameter class updates and returns the value of the parameter object. This method can be overridden by different parameter classes to make it return an appropriate value.
The binding of the parameters and the actual values in the parameter class depends on the method used by the provider to handle and recognize parameters. For instance if named parameters are supported the binding will occur if names of the placeholders match with the names of the parameters. Otherwise matching can be based on position. This is a typical scenario when OLE DB is used to access the data;
Caching is required for improving application performance and for data source controls. Data is retrieved and made available to other components within the application faster if caching is available. The SqlDataSource control can be instructed to cache data in the data source mode—DataSet. It provides for automatic caching of data using time based cache expiration policy or on the basis of the SqlCacheDependency expiration policy. To enable automatic caching the EnableCaching property has to be set to True and the CacheDuration property value should be set to a non zero value. An absolute expiration property is used by default but this can be configured by setting a value to the CacheExpirationPolicy property. SqlCacheDependency binds to a timestamp of the SQL Server table. It forms an expiration based on the dependency between the SQL server database and the contents of the control. The dependency is defined as a string property with the syntax “database:table”. Multiple table dependencies can be specified using colons. This feature can also be used to invalidate related values in the cache if the contents in the table changes. This is useful when an update can force a refresh on the page.
In this section of the tutorial we have examined in some detail the codeless way in ASP.NET 2.0 enables users to connect to data sources from a web application. In the next section we shall study the Data Source Wizard which makes this task even easier.