Walkthrough: Using the ObjectDataSource with an XML File
Many Web applications are built by using multiple tiers, with one or more components in the middle tier to provide data access. Creating a custom middle tier business object allows you to implement your own business logic. This walkthrough illustrates how to create a basic business object that you can use as a data source for ASP.NET Web Forms pages.
During this walkthrough, you will learn how to:
Create a component that can return data to a Web page. The component uses an XML file for its data.
Reference the business object as a data source on a Web page.
Bind a control to the data returned by the business object.
Read and write data by using the business object.
In order to complete this walkthrough, you will need:
Visual Web Developer (Visual Studio).
The .NET Framework.
This walkthrough assumes that you have a general understanding of how to use Visual Web Developer.
If you have already created a Web site in Visual Web Developer (for example, by following the steps in Walkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site and go to the next section, "Creating an XML File for Business Data." Otherwise, create a new Web site and page.
This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio.
Open Visual Web Developer.
On the File menu, click NewWeb Site.
The New Web Site dialog box appears.
Under Visual Studio installed templates, click ASP.NET Web Site.
In the Location box, enter the name of the folder where you want to keep the pages of your Web site.
For example, type the folder name C:\WebSites.
In the Language list, click the programming language you prefer to work in.
Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
In the following procedure, you will create a simple XML file for the business component data.
In Solution Explorer, right-click App_Data, and then click AddNew Item.
注意
Be sure you create the XML file in the App_Data folder. The App_Data folder has permissions set on it that will allow the Web page to read and write data to the XML file.
Under Visual Studio installed templates, click XML file.
In the Name box, type Authors.xml.
Click Add.
A new XML file is created that contains only the XML directive.
Copy the following XML data, and then paste it into the file, overwriting what is already in the file.
The XML file includes schema information that identifies the database structure of the data, including a primary-key constraint for the key.
注意
Business components can work with data in any way that is suitable for your application. This walkthrough uses an XML file.
<?xml version="1.0" standalone="yes"?> <dsPubs xmlns="https://www.tempuri.org/dsPubs.xsd"> <xs:schema id="dsPubs" targetNamespace="https://www.tempuri.org/dsPubs.xsd" xmlns:mstns="https://www.tempuri.org/dsPubs.xsd" xmlns="https://www.tempuri.org/dsPubs.xsd" xmlns:xs="https://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified"> <xs:element name="dsPubs" msdata:IsDataSet="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="authors"> <xs:complexType> <xs:sequence> <xs:element name="au_id" type="xs:string" /> <xs:element name="au_lname" type="xs:string" /> <xs:element name="au_fname" type="xs:string" /> <xs:element name="au_phone" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> <xs:unique name="Constraint1" msdata:PrimaryKey="true"> <xs:selector xpath=".//mstns:authors" /> <xs:field xpath="mstns:au_id" /> </xs:unique> </xs:element> </xs:schema> <authors> <au_id>172-32-1176</au_id> <au_lname>West</au_lname> <au_fname>Paul</au_fname> <au_phone>408 555-0123</au_phone> </authors> <authors> <au_id>213-46-8915</au_id> <au_lname>Gray</au_lname> <au_fname>Chris</au_fname> <au_phone>415 555-0120</au_phone> </authors> </dsPubs>
Save the Authors.xml file, and then close it.
The next step is to create a class to act as your business component. You will keep the component in the App_Code folder of your Web site. In a real application, you can keep the component in any convenient store, including the global assembly cache. If your Web site does not already have a directory named App_Code, you must create one.
In Solution Explorer, right-click the name of your Web site, click Add ASP.NET Folder, and then click App_Code.
注意
The folder must be named App_Code.
You can now add the component to your site.
In Solution Explorer, right-click the App_Code folder, and then click Add New Item.
注意
Be sure to create the new item in the App_Code folder.
The Add New Item dialog box appears.
Under Visual Studio installed templates, click Class.
In the Language box, click the programming language you prefer.
In the Name box, type BusinessObject.
Click Add.
Visual Web Developer creates the new class file and opens the code editor.
Copy the following code, and then paste it into the file, overwriting what is already in the file.
Imports Microsoft.VisualBasic Imports System Imports System.Web Imports System.Data Namespace PubsClasses Public Class AuthorClass Private dsAuthors As DataSet = _ New System.Data.DataSet("ds1") Private filePath As String = _ HttpContext.Current.Server.MapPath _ ("~/App_Data/authors.xml") Public Sub New() dsAuthors.ReadXml(filePath, Data.XmlReadMode.ReadSchema) End Sub Public Function GetAuthors() As DataSet Return dsAuthors End Function End Class End Namespace
using System; using System.Web; using System.Data; namespace PubsClasses { public class AuthorClass { private DataSet dsAuthors = new DataSet("ds1"); private String filePath = HttpContext.Current.Server.MapPath ("~/App_Data/Authors.xml"); public AuthorClass() { dsAuthors.ReadXml (filePath, XmlReadMode.ReadSchema); } public DataSet GetAuthors () { return dsAuthors; } } }
注意
Make sure the value of the filePath variable references the name of the XML file that you created previously.
When an instance of the class is created, it reads the XML file and translates it into a dataset. The class's GetAuthors method returns the dataset.
Save the file. You must save the file for the next section to work properly.
You can now invoke the business component in a Web page and display its data. To reference the component, you use an ObjectDataSource control, which is specifically designed to work with objects.
Switch to or open the Default.aspx page.
注意
If you do not have a Default.aspx page, you can use another page. Alternatively, you can add a new page to the Web site. In Solution Explorer, right-click the name of your Web site, click Add New Item, and then add a Web Form.
Switch to Design view.
In the Toolbox, from the Data folder, drag an ObjectDataSource control onto the page.
In the Properties window, set ID to AuthorsObjectDataSource.
Right-click the ObjectDataSource control, and then click the smart tag to display the ObjectDataSource Tasks menu.
On the ObjectDataSource Tasks menu, click Configure Data Source.
The Configure Data Source wizard appears.
In the Choose your business object list, click PubsClasses.AuthorClass.
Click Next.
In the Select tab, in the Choose a method list, click GetAuthors(), returns Dataset.
The GetAuthors method is defined in the business class you created previously. It returns a dataset containing the data from the Authors.xml file.
Click Finish.
The configuration information you have entered specifies that to get data from the component, the component's GetAuthors method should be called.
注意
The name of the method you specify for the SelectMethod property is case-sensitive, even if you are programming in Visual Basic .NET.
You can now get data from the component by using the ObjectDataSource control. You will display the data in a GridView control on the page.
In the Toolbox, from the Data folder, drag a GridView control onto the page.
Right-click the GridView control, and then click the smart tag if the Common GridView Tasks menu is not showing.
On the Common GridView Tasks menu, in the Choose Data Source box, click AuthorsObjectDataSource.
Press CTRL+F5 to run the page.
The GridView control with the XML data in it is displayed.
As with other data source controls, such as the SqlDataSource control, the ObjectDataSource control supports updating (inserting, updating, and deleting). In this section, you will modify the business component with a method that inserts an author record. Then you will change the page so that users can type new author information and modify the ObjectDataSource control to perform the insertion.
注意
During this part of the walkthrough, the Authors.xml file you created previously will be updated. It is important that the application have permission to write to the file at run time or the Web page will display an error when you try to update the file. If you created the Authors.xml file in the App_Data folder, permissions are set automatically.
Switch to the BusinessObject file.
Add the following method as the final member of AuthorClass.
Public Sub InsertAuthor(ByVal au_id As String, _ ByVal au_lname As String, _ ByVal au_fname As String, ByVal au_phone As String) Dim workRow As DataRow = dsAuthors.Tables(0).NewRow workRow.BeginEdit() workRow(0) = au_id workRow(1) = au_lname workRow(2) = au_fname workRow(3) = au_phone workRow.EndEdit() dsAuthors.Tables(0).Rows.Add(workRow) dsAuthors.WriteXml(filePath, Data.XmlWriteMode.WriteSchema) End Sub
public void InsertAuthor (String au_id, String au_lname, String au_fname, String au_phone) { DataRow workRow = dsAuthors.Tables[0].NewRow (); workRow.BeginEdit (); workRow[0] = au_id; workRow[1] = au_lname; workRow[2] = au_fname; workRow[3] = au_phone; workRow.EndEdit (); dsAuthors.Tables[0].Rows.Add (workRow); dsAuthors.WriteXml (filePath, XmlWriteMode.WriteSchema); }
注意
Pay close attention to the names of the variables used to pass author information into the method (au_id, au_lname, au_fname, and au_phone). They must match the column names defined in the schema of the XML file you created previously.
The new method takes four values to insert, which you will provide in the page as parameters. The method creates a new row in the dataset, and then writes the updated dataset out as an XML file.
Save the file.
The next step is to change the page so that users can enter new author information. For the following procedure, you will use the DetailsView control.
Switch to or open the Default.aspx page.
Switch to Design view.
In the Toolbox, from the Data folder, drag a DetailsView control onto the page.
注意
The exact layout of the page is not important.
On the DetailsView Tasks menu, in the Choose Data Source box, click AuthorsObjectDataSource.
注意
If the DetailsView Tasks menu is not visible, click the smart tag.
In the Properties window, set AutoGenerateInsertButton to true.
This causes the DetailsView control to render a New button that users can click to put the control into data-entry mode.
Finally, you must configure the ObjectDataSource control to specify what action the control should take to insert data.
Right-click AuthorsObjectDataSource, click Properties, and then set InsertMethod to InsertAuthor.
This is the name of the method that you added to the business component.
You can now insert new authors into the XML file.
Press CTRL+F5 to run the Default.aspx page.
In the DetailsView control, click the New button.
The control is redisplayed with text boxes.
Enter new author information, and then click Insert.
The new author information is added to the XML file. The GridView control immediately reflects the new record.
This walkthrough illustrates how to work with a data component. You might want to experiment with additional features of navigation. For example, you might want to:
Add update and delete functionality. To do so, you would add methods to the component. Doing so is similar to adding the insertion logic — you add a method to the component, configure the data source control to invoke the component method, add appropriate parameters, and add a line of code to call the Update and Delete methods of the data source control. For details, see Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control.
Change the business component to work with database data instead of with an XML file. You do not need to make any changes to the controls on the page.
Restrict which users can make changes to the data. A typical method is to add membership and roles to your Web site, and then establish rules that the business component can check before allowing changes to data. For details, see Walkthrough: Creating a Web Site with Membership and User Login and Walkthrough: Managing Web Site Users with Roles.
Walkthrough: Using Shared Code in Web Sites in Visual Web Developer
Walkthrough: Creating a Basic Web Forms Page in Visual Studio