| By Paul Ballard | Article Rating: |
|
| July 6, 2004 12:00 AM EDT | Reads: |
16,237 |
In my previous article (.NETDJ, Vol. 2, issue 4) we took a look at how ASP.NET v2.0's SqlDataSource control allows Web developers to create a dynamic Web site using data stored in a SQL database with little or no server code. In this article we're going to build on that by delving into some of the other new DataSource controls and how we can integrate data from non SQL sources into an interactive Web page.
XmlDataSource
The XmlDataSource is a new server control used to provide access to hierarchical data stored as XML. The first step in defining an XmlDataSource is to specify the location of the data to be retrieved. The data can be stored in an external file or defined within the XmlDataSource control itself. To specify the file that contains the data, set the DataFile property to the physical or relative path of the file. To embed the data within the HTML definition of the control, use the <data> subelement. Note: Using the PDC bits, embedding XML data in the HTML of the XmlDataSource control causes an error in the Visual Studio Designer; however, it compiles and runs just fine.
Simple access to XML files is just the beginning of the features of this control. You can also transform the data before it is bound by specifying a file containing a standard XSL style sheet using the TransformFile property. This transformation is automatically applied before the data reaches any bound controls. In addition to specifying a file, you can also embed the XSL in the HTML definition of the XmlDataSource control using the <transform> subelement.
Listing 1 shows XML data containing a hierarchical list of employees based on the Northwind Employees table. Listing 2 is a simple XSL transformation to combine the first and last names into a single attribute and to convert the ID to an attribute for each Employee node. The following code shows the definition of an XmlDataSource that will read in the data from a file, apply the transformation from the XSLT file, and then make the data available to be bound to a control, without any server-side code.
<asp:xmldatasource id="xdsSalesStaff" runat="server" datafile="SalesStaff.xml"
transformfile="SalesTransform.xslt">
</asp:xmldatasource>
The XmlDataSource is then bound to a TreeView control that can show the hierarchical relationship of the data, which is the org chart for the Northwind Sales team. To bind the data to the control set, the TreeView's DataSourceID property to the ID of the XmlDataSource control.
In addition to transformations, you can also specify an XML Schema to define the data types contained in the XML. This is useful for ensuring that when the data is bound to a control, it is bound as the correct type instead of always binding as a string. To use a schema from a file, set the SchemaFile property of the XmlDataSource control to that file's path. Both the schema and the transformation can also be embedded directly into the XmlDataSource control using the <schema> and <transform> subelements.
You can specify a subsection of the XML to be used for binding by declaring an XPath string used to filter the XML. This is done with the XPath property and can be any valid XPath query. It has a similar filtering effect as the RowFilter property of an ADO.NET DataView class.
Another very useful function of the XmlDataSource control is the ability to automatically save any changes to the XML before the page is rendered. This allows you to use XML in much the same way you would use a database including updates, insertions, and deletions. To enable this, set the XmlDataSource's AutoSave property to true.
While coding is not necessary for this DataSource control, it does expose events that you can use during the data binding process. In addition to the events inherited from DataSourceControl, the XmlDataSource adds an event called Transforming, which is called when and if the XML data is being transformed. In HTML, you define the method to call using the onTransforming attribute and specifying the method name to call. In this method, you can set any parameters necessary for the transformation using the XmlDataSource's TransformArgumentList property. This property is a specialized collection called an XsltArgumentList and can be found in the System.XML namespace.
DataSetDataSource
The DataSetDataSource is almost identical to the XmlDataSource both in features and properties. Both controls use XML data as their underlying persistence mechanism. The DataSetDataSource control, however, allows you to work with the data as either an ADO.NET DataSet or an XmlDocument. This provides great flexibility but also takes up more resources. The only property of the XmlDataSource control that isn't supported on the DataSetDataSource control is the XPath property. The DataSetDataSource control also adds another method called GetDataSet(), which returns the data as an ADO.NET DataSet bound to the XML data. Any changes to the DataSet will result in changes to the XML.
ObjectDataSource
The DataSource controls that we've described thus far have all been based on a two-tiered architecture, meaning that the user interface implements logic that works directly with the data. In most enterprise-level applications, the business logic and/or the data need to be moved away from the user interface for scalability, reliability, etc. In ASP.NET v1.x, the middle tier(s) would expose some sort of custom business objects to the user interface and then a developer would bind the data to the controls programmatically. Now this binding code is no longer necessary thanks to the ObjectDataSource control.
The ObjectDataSource control is used to instantiate another object that will then be responsible for accessing and handling any modifications to the data. Therefore, the first property you need to set for this control is the TypeName property that tells the control in which class to create an instance. This can be the name of any class included in or referenced by the user interface assembly as long as it has a default public constructor (no parameters).
Next, you specify the methods of the object, which will handle Select, Update, Insert, or Delete requests. As with the SqlDataSource control, you can implement any combination of these operations that you require. To specify a method used to retrieve data, set the SelectMethod property. The select method must return an object that can be bound to a control such as a Dataset, XmlDocument, or Collection. If the method being invoked requires parameters, you can specify the parameters using the SelectParameters collection which in HTML is defined using the <selectparameters> sub element.
To illustrate how the ObjectDataSource control works, I'm actually going to bind it directly to a Web service. The first thing to do is to add the Web reference to your Web site. The Web service I'll be using is called SalesTracking and has a service called SalesMgr. The SalesMgr service exposes one method, GetSalesPerDay, which in turn takes one parameter, the ID of the employee to return data for. In the Web method, I simulate querying a data source for the last 15 days item sales for that employee. I return the data as a dataset with one table having two columns, Date and Sales.
After adding my Web reference, I set the TypeName property of the ObjectDataSource to "SalesTracking. SalesMgr". This will cause the ObjectDataSource to create an instance of this class. Next, I set the SelectMethod property to "GetSalesPerDay" and create a SelectParameters collection. To fill the EmployeeID parameter of my Select method, I'll use a ControlParameter and link it to the selected node of the TreeView control used in the XmlDataSource example. Now, when a user selects an employee from the TreeView control, the ObjectDataSource will use that employee's ID as input to its select method. The best part is that all of this is accomplished without writing a single line of code. Here is an example of the completed ObjectDataSource control.
<asp:objectdatasource id="odsDailySales" runat="server"
typename="SalesService.SalesMgr"
selectmethod="SalesPerDay">
<selectparameters>
<asp:controlparameter name="EmployeeID" propertyname="SelectedValue"
type="Int32" controlid="tvSalesStaff">
</asp:controlparameter>
</selectparameters>
</asp:objectdatasource>
The ObjectDataSource control has several custom events that can be used during the data binding process. Similar to the SqlDataSource control, there are two events for each operation: one being fired before the operation is called and one after the operation is complete. For example, if you wanted to invoke a custom method after the select method is invoked, you would handle the Selected event. In HTML, this is done by defining an onSelected attribute with the value set to the method to be invoked. To invoke a method before the Select method is called, you would in turn handle the Selecting event.
In addition to the operation-based events, the ObjectDataSource also defines two other events: ObjectCreated and ObjectDisposing. The ObjectCreated event is fired after the data object is instantiated and can be used to set any properties or perform any initialization necessary before an operation method is invoked. The ObjectDisposing method is called just before the object is disposed and can be used to free up any resources not disposed directly by the data object itself.
SiteMapDataSource
Web site navigation support in ASP.NET v1.x is sorely lacking. In v2.0, navigation is supported to not only dynamically build menus, but also to let users know where they are on the site and how to get back to where they originated. This feature is facilitated using the concept of a SiteMap. It defines all of the navigable pages of your site and their hierarchical relationship to one another. It is exposed to the Web application by a SiteMapProvider. This provider can be anything from a simple XML file to a custom provider accessing a content management system. The default provider defined in the machine.config file allows the Web developer to specify the full sitemap in an XML file called app.sitemap.
The default SiteMapProvider uses a specific XML schema to define the syntax for the app.sitemap file. This syntax is a simple list of nested elements called siteMapNodes. Each node has several attributes, of which the most important are Title and Url. By setting these attributes for each element, and embedding those elements in a hierarchy that represents our site, the SiteMapProvider can determine not only what navigation options are available but also where the current page exists in the sitemap. Listing 3 shows a sample sitemap with several nodes.
To be able to bind this data to a control on our page, use the new SiteMapDataSource control. You can use this control to bind the sitemap data to a user interface control that you can then use as a navigation aid such as a menu. The first step in defining a SiteMapDataSource control is to set the SiteMapProvider property. However, if you are using the default provider, you can skip this step and the default SiteMapProvider will be used. The next property to set is the SiteMapViewType property. This property is used to determine how the data will be represented. The possible options are Tree, Flat, and Path. Tree mode means that the data will be represented using the hierarchies defined in the sitemap, much like an XML document. The Flat mode has the data returned as a flat list of elements with no relationships defined. If you choose the Flat view mode you can also set the FlatDepth property to an integer representing at what depth in the node tree the hierarchy is flattened. The Path mode is used to return only the nodes from the root node to the current page.
Here is the syntax for a SiteMapDataSource control that returns the data in Tree mode for binding to a TreeView control. This control will be used as a site navigation menu. Note that it uses the default SiteMapProvider and therefore doesn't require setting the SiteMapProvider property.
<asp:sitemapdatasource id="sdsMenu" runat="server" sitemapviewtype="Tree" />
The other properties available with this control are used to specify where in the node list the data returned for binding should start. These are StartingDepth, StartingNodeType, and StartingUrl. StartingDepth is an integer that sets the starting node level for the data returned. StartingNodeType is an enumeration and can be either Root (Default), Parent, or Current. Lastly, StartingUrl specifies the starting node by URL.
All of the new DataSource controls add quick and easy access to data including caching, paging, and parameterized operation support. And the best part is that they do it without writing tedious, repetitive server code. In future versions of the .NET Framework, there may be other DataSource controls that can be downloaded to provide access to data in other formats. You can look forward to all of these controls and more in ASP.NET v2.
Published July 6, 2004 Reads 16,237
Copyright © 2004 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Paul Ballard
Paul Ballard is an MCSD, MCAD, and MCSE certified consultant and president of the Rochester Consulting Partnership, Inc. He has more than 15 years of experience designing and building Windows- and Web-based distributed applications and is currently specializing in Microsoft's .NET technologies as a consultant, speaker, and trainer. Paul is also a volunteer with INETA and the founder of the Central Pennsylvania .NET User Group.
![]() |
chetan 08/13/04 07:16:21 AM EDT | |||
I have few query i hope u will be able to help me. I have oracle server 8.0.3 I having problem with oracle SqlDataSource using System.Data.Oledb . I request you if can try simple task of searching with like query from textbox on oracle database table. Heres the code ............................ " ProviderName="<%$ ConnectionStrings:SamitConnection.ProviderName %>" SelectCommand="SELECT STATUS, ESTATUS, EMODE, EID, QTY, EDATE, PARTY, PROD_NAME FROM VIEW_ENQUIRY WHERE PARTY LIKE ''%'' + ? + ''%'' ORDER BY EDATE, PARTY"> |
||||
- Kindle 2 vs Nook
- Confessions of a Ulitzer Addict
- IBM Hardware Chief, Intel VC Exec Arrested in Insider Trading Scam
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- Ulitzer.com Named Exclusive "New Media" Sponsor of Cloud Computing Conference & Expo
- Infrastructure-as-a-Service Will Mature in 2010: Microsoft's David Chou
- Windows 7 – Microsoft’s First Step to the Cloud
- Cloud Expo and the End of Tech Recession
- Jill Tummler Singer, Deputy CIO of CIA, Keynotes at GovIT Expo
- Reality Check at the Cloud Computing Expo
- Visual Studio 2010 Is Cloud Friendly
- Fired SCO CEO Fires Back
- Kindle 2 vs Nook
- The Difference Between Web Hosting and Cloud Computing
- Ajax in RichFaces 3.3, JSF 2 and RichFaces 4
- Confessions of a Ulitzer Addict
- Wave on Ulitzer: Confessions of a Google Wave Fanboy
- IBM Hardware Chief, Intel VC Exec Arrested in Insider Trading Scam
- Cloud Computing Best Practices
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- Ulitzer.com Named Exclusive "New Media" Sponsor of Cloud Computing Conference & Expo
- Infrastructure-as-a-Service Will Mature in 2010: Microsoft's David Chou
- Eval JavaScript in a Global Context
- Windows 7 – Microsoft’s First Step to the Cloud
- Google Maps and ASP.NET
- Crystal Reports XI & How It Has Changed
- Converting VB6 to VB.NET, Part I
- Creating Controls for.NET Compact Framework in Visual Studio 2005
- Where Are RIA Technologies Headed in 2008?
- How to Write High-Performance C# Code
- AJAX World RIA Conference & Expo Kicks Off in New York City
- Implementing Tab Navigation with ASP.NET 2.0
- i-Technology Photo Exclusive: Bill Gates & Steve Jobs In "Nerds"
- .NET Archives: Getting Reacquainted with the Father of C#
- i-Technology Viewpoint: "SOA Sucks"
- Programmatically Posting Data to ASP .NET Web Applications





























