Partager via


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.

Prerequisites

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.

Creating the Web Site

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.

To create a file system Web site

  1. Open Visual Web Developer.

  2. On the File menu, click NewWeb Site.

    The New Web Site dialog box appears.

  3. Under Visual Studio installed templates, click ASP.NET Web Site.

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

  5. In the Language list, click the programming language you prefer to work in.

  6. Click OK.

    Visual Web Developer creates the folder and a new page named Default.aspx.

Creating an XML File for Business Data

In the following procedure, you will create a simple XML file for the business component data.

To create the XML file

  1. In Solution Explorer, right-click App_Data, and then click AddNew Item.

    Note

    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.

  2. Under Visual Studio installed templates, click XML file.

  3. In the Name box, type Authors.xml.

  4. Click Add.

    A new XML file is created that contains only the XML directive.

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

    Note

    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>
    
  6. Save the Authors.xml file, and then close it.

Creating a Component

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.

To create an App_Code folder

  • In Solution Explorer, right-click the name of your Web site, click Add ASP.NET Folder, and then click App_Code.

    Note

    The folder must be named App_Code.

You can now add the component to your site.

To create the business component

  1. In Solution Explorer, right-click the App_Code folder, and then click Add New Item.

    Note

    Be sure to create the new item in the App_Code folder.

    The Add New Item dialog box appears.

  2. Under Visual Studio installed templates, click Class.

  3. In the Language box, click the programming language you prefer.

  4. In the Name box, type BusinessObject.

  5. Click Add.

    Visual Web Developer creates the new class file and opens the code editor.

  6. 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;
            }
        }
    }
    

    Note

    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.

  7. Save the file. You must save the file for the next section to work properly.

Displaying Data by Using the Business Component

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.

To create an ObjectDataSource control that references the component

  1. Switch to or open the Default.aspx page.

    Note

    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.

  2. Switch to Design view.

  3. In the Toolbox, from the Data folder, drag an ObjectDataSource control onto the page.

  4. In the Properties window, set ID to AuthorsObjectDataSource.

  5. Right-click the ObjectDataSource control, and then click the smart tag to display the ObjectDataSource Tasks menu.

  6. On the ObjectDataSource Tasks menu, click Configure Data Source.

    The Configure Data Source wizard appears.

  7. In the Choose your business object list, click PubsClasses.AuthorClass.

  8. Click Next.

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

  10. Click Finish.

    The configuration information you have entered specifies that to get data from the component, the component's GetAuthors method should be called.

    Note

    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.

To display data from the component

  1. In the Toolbox, from the Data folder, drag a GridView control onto the page.

  2. Right-click the GridView control, and then click the smart tag if the Common GridView Tasks menu is not showing.

  3. On the Common GridView Tasks menu, in the Choose Data Source box, click AuthorsObjectDataSource.

  4. Press CTRL+F5 to run the page.

    The GridView control with the XML data in it is displayed.

Inserting Data by Using the Business Component

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.

Note

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.

To modify the business component to allow inserts

  1. Switch to the BusinessObject file.

  2. 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);
    }
    

    Note

    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.

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

To add a control for inserting data

  1. Switch to or open the Default.aspx page.

  2. Switch to Design view.

  3. In the Toolbox, from the Data folder, drag a DetailsView control onto the page.

    Note

    The exact layout of the page is not important.

  4. On the DetailsView Tasks menu, in the Choose Data Source box, click AuthorsObjectDataSource.

    Note

    If the DetailsView Tasks menu is not visible, click the smart tag.

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

To configure the data source control for inserting 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.

To test insertion

  1. Press CTRL+F5 to run the Default.aspx page.

  2. In the DetailsView control, click the New button.

    The control is redisplayed with text boxes.

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

Next Steps

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:

See Also

Tasks

Walkthrough: Using Shared Code in Web Sites in Visual Web Developer

Walkthrough: Creating a Basic Web Forms Page in Visual Studio

Concepts

Using Parameters with Data Source Controls for Filtering

Other Resources

ObjectDataSource Web Server Control Overview