Using XSD Schema Files to Load and Save a DataSet Structure

Problem

You need to create an XSD schema from a DataSet and define the schema of a DataSet from an XSD schema.

Solution

Use the XmlTextWriter and XmlTextReader classes.

The sample code contains three event handlers:

Write Button.Click

Creates a DataSet containing the Orders table and Order Details table from Northwind and a relation between the two. The XSD schema for the DataSet is written both to a file and to a text box on the form.

Read Button.Click

Creates a DataSet and reads in the schema from a file containing a previously serialized XSD schema. The XSD schema is written from the DataSet to a stream and displayed.

Clear Button.Click

Clears the DataGrid and the result text box.

The C# code is shown in Example 8-1.

Example 8-1. File: XsdSchemaFileForm.cs

// Namespaces, variables, and constants
using System;
using System.Configuration;
using System.Windows.Forms;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Data;
using System.Data.SqlClient;

// Table name constants
private const String ORDERS_TABLE = "Orders";
private const String ORDERDETAILS_TABLE = "OrderDetails";

// Relation name constants
private const String ORDERS_ORDERDETAILS_RELATION =
 "Orders_OrderDetails_Relation";

// Field name constants
private const String ORDERID_FIELD = "OrderID";

// . . . 

private void writeSchemaButton_Click(object sender, System.EventArgs e)
{
 DataSet ds = new DataSet( );
 
 SqlDataAdapter da;

 // Fill the Order table and add it to the DataSet.
 da = new SqlDataAdapter("SELECT * FROM Orders",
 ConfigurationSettings.AppSettings["Sql_ConnectString"]);
 DataTable orderTable = new DataTable(ORDERS_TABLE);
 da.FillSchema(orderTable, SchemaType.Source);
 da.Fill(orderTable);
 ds.Tables.Add(orderTable);

 // Fill the OrderDetails table and add it to the DataSet.
 da = new SqlDataAdapter("SELECT * FROM [Order Details]",
 ConfigurationSettings.AppSettings["Sql_ConnectString"]);
 DataTable orderDetailTable = new DataTable(ORDERDETAILS_TABLE);
 da.FillSchema(orderDetailTable, SchemaType.Source);
 da.Fill(orderDetailTable);
 ds.Tables.Add(orderDetailTable);

 // Create a relation between the tables.
 ds.Relations.Add(ORDERS_ORDERDETAILS_RELATION,
 ds.Tables[ORDERS_TABLE].Columns[ORDERID_FIELD],
 ds.Tables[ORDERDETAILS_TABLE].Columns[ORDERID_FIELD],
 true);

 // Bind the default view of the Orders table to the grid.
 resultDataGrid.DataSource = ds.Tables[ORDERS_TABLE].DefaultView;

 // Write the XSD schema to a file.
 // Display file dialog to select XSD file to write.
 SaveFileDialog sfd = new SaveFileDialog( );
 sfd.InitialDirectory = System.IO.Path.GetTempPath( );
 sfd.Filter = "XSD Files (*.xsd)*.xsdAll files (*.*)*.*";
 sfd.FilterIndex = 1;

 if (sfd.ShowDialog( ) == DialogResult.OK)
 {
 FileStream fs = new FileStream(sfd.FileName, FileMode.Create,
 FileAccess.Write);
 // Create an XmlTextWriter using the file stream.
 XmlTextWriter xtw = new XmlTextWriter(fs, Encoding.Unicode);

 try
 {
 // Write the XSD schema to the file.
 ds.WriteXmlSchema(xtw);

 resultTextBox.Text="XSD file written.";
 }
 catch(Exception ex)
 {
 MessageBox.Show(ex.Message);
 }
 finally
 {
 xtw.Close( );
 }
 }
}

private void readSchemaButton_Click(object sender, System.EventArgs e)
{
 // Write the XSD schema from a file.
 // Display file dialog to select XSD file to read.
 OpenFileDialog ofd = new OpenFileDialog( );
 ofd.InitialDirectory = System.IO.Path.GetTempPath( );
 ofd.Filter = "XSD Files (*.xsd)*.xsdAll files (*.*)*.*";
 ofd.FilterIndex = 1;

 if (ofd.ShowDialog( ) == DialogResult.OK)
 {
 FileStream fs = new FileStream(ofd.FileName, FileMode.Open,
 FileAccess.Read);
 // Create an XmlTextReader using the file stream.
 XmlTextReader xtr = new XmlTextReader(fs);
 
 try
 {
 // Read the schema into the DataSet.
 DataSet ds = new DataSet( );
 ds.ReadXmlSchema(xtr);

 // Bind the default view of the Orders table to the grid.
 resultDataGrid.DataSource =
 ds.Tables[ORDERS_TABLE].DefaultView;

 // Write the XSD schema to a memory stream and
 // display the XSD schema.
 MemoryStream ms = new MemoryStream( );
 ds.WriteXmlSchema(ms);
 byte[] result = ms.ToArray( );
 ms.Close( );

 resultTextBox.Text =
 Encoding.UTF8.GetString(result, 0, result.Length);
 }
 catch(Exception ex)
 {
 MessageBox.Show(ex.Message);
 }
 finally
 {
 xtr.Close( );
 }
 }
}

private void clearButton_Click(object sender, System.EventArgs e)
{
 // Clear the data grid and the result text box.
 resultDataGrid.DataSource = null;
 resultTextBox.Clear( );
}

Discussion

The solution uses the XmlTextWriter and XmlTextReader classes to write and read the XSD schema information. The XmlTextWriter is a writer that provides a fast, non-cached, forward-only way to generate streams or files of XML data. The encoding generated is specified using one of the static property values from System.Text.Encoding described in Table 8-1.

Table 8-1. Character encoding members of the System.Text.Encoding class

Encoding

Description

ASCII

ASCII (7 bit) character set

BigEndianUnicode

Unicode format in big-endian byte order

Default

Encoding for system's current ANSI code page

Unicode

Unicode format in little-endian byte order

UTF7

UTF-7 format

UTF8

UTF-8 format. This is the default

The XmlTextReader provides fast, non-cached, forward-only access to XML data. The XmlTextReader does not validate the XML. For validation, use the XmlValidatingReader class.

The XmlTextWriter and XmlTextReader classes conform to the W3C XML 1.0 and the Namespaces in XML recommendations.

For more information about the XmlTextWriter and XmlTextReader classes, see the MSDN Library.

The WriteXmlSchema( ) and ReadXmlSchema( ) methods of the DataSet class are used to write and read the XSD schema for the XML data. The schema is written using the XSD standard and includes tables, relations, and constraint definitions. Example 8-2 shows the XSD schema written by this solution.

Example 8-2. Orders with order details XSD schema


 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Use the WriteXml( ) and ReadXml( ) methods of the DataSet to write and read the XML data in addition to the schema information.

Connecting to Data

Retrieving and Managing Data

Searching and Analyzing Data

Adding and Modifying Data

Copying and Transferring Data

Maintaining Database Integrity

Binding Data to .NET User Interfaces

Working with XML

Optimizing .NET Data Access

Enumerating and Maintaining Database Objects

Appendix A. Converting from C# to VB Syntax



ADO. NET Cookbook
ADO.NET 3.5 Cookbook (Cookbooks (OReilly))
ISBN: 0596101406
EAN: 2147483647
Year: 2002
Pages: 222
Authors: Bill Hamilton

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net