Home > Articles > Web Services > XML

This chapter is from the book

This chapter is from the book

7.4 Typed DataSets

One of the functions performed by XSD.exe, the XML schema generation tool, is to generate a typed DataSet from an XSD schema. This functionality is also available in Visual Studio as a menu item and context menu entry on an existing "DataAdapter object." What exactly is a typed DataSet?

A typed DataSet is a subclass of System.Data.DataSet in which the tables that exist in the DataSet are derived by reading the XSD schema information. The difference between a typed DataSet and an "ordinary" DataSet is that the DataRows, DataTables, and other items are available as strong types; that is, rather than refer to DataSet.Tables[0] or DataSet.Tables["customers"], you code against a strongly typed DataTable named, for example, MyDataSet.Customers. Typed DataSets have the advantage that the strongly typed variable names can be checked at compile time rather than causing errors at runtime. A short example will illustrate this concept.

Suppose you have a DataSet that should contain a table named customers. It should have columns named custid and custname. You can refer to the table and the columns by ordinal or by name. As shown in Listing 7–21, the data is loosely typed when referred to by ordinal or name, meaning that the compiler cannot guarantee that you've spelled the column name correctly or used the correct ordinal. The problem is that the error informing you of this occurs at runtime rather than at compile time. If the DataSet items were strongly typed, misspelling the column name or using the wrong ordinal would be prevented because the code simply would not compile.

Listing 7–21 Referring to DataTables and Columns

DataSet ds = new DataSet();
// some action to load the DataSet...

// this will fail if second table does not exist
String name = ds.Tables[1].TableName;
// this will fail if the table is named customers
DataTable t = ds.Tables["customesr"];

// This will fail if the DataRow r has fewer than 5 columns
// or if column 5 is a String data type
DataRow r;
int value = (int)r[4];
// This will fail if there is a column named "custname"
String value = r["custnam"].ToString();

This does not solve every problem; mismatches can still occur if the database schema changes between the time the typed DataSet was generated and runtime. But because the structure of the DataSet is built into the names, the compiler can catch the misspellings. The examples in Listing 7–22 illustrate this.

Listing 7–22 Strong typing in DataSet

// this fails at compile time if the name of 
// the table should be "customers"
DataTable t = MyDataSet.Customesr;

// so does this, should be custname
String value = MyDataSet.Customers[0].custnam;

The easiest way to generate a typed DataSet corresponding to an existing database resultset is through Visual Studio or XSD.exe, using an existing table, stored procedure, SQL statement, or in the case of XSD.exe, an XML schema. In Visual Studio, you can create a typed DataSet from any DataAdapter object that has been dropped on a form, as shown in Figure 7–2. The Visual Studio designer instan

The manual equivalent of this is to Fill a DataSet, save the schema with DataSet.WriteXmlSchema, and then use the schema as input into XSD.exe. For example, let's generate a typed DataSet for the simple one-table case shown in Listing 7–23 and see what we get.

Figure 7-2Figure 7-2 Generating a typed DataSet in Visual Studio.

Listing 7–23 Producing input for a typed DataSet

SqlDataAdapter da = new SqlDataAdapter(
  "select * from jobs",
  "server=localhost;uid=sa;database=pubs");

// name the DataSet MyDS
DataSet ds = new DataSet("MyDS");

// name the table MyTable
da.Fill(ds, "MyTable");

ds.WriteXmlSchema("myschema.xsd");

Listing 7–24 shows the complete source code for the sample typed DataSet.

Listing 7–24 A typed DataSet subclass generated by XSD.exe

// 
// This source code was auto-generated by xsd
// 
using System;
using System.Data;
using System.Xml;
using System.Runtime.Serialization;


[Serializable()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Diagnostics.DebuggerStepThrough()]
[System.ComponentModel.ToolboxItem(true)]
public class JobsDS : DataSet {
    
  private jobsDataTable tablejobs;
    
    public JobsDS() {
        this.InitClass();
        System.ComponentModel.CollectionChangeEventHandler
          schemaChangedHandler = new 
          System.ComponentModel.CollectionChangeEventHandler(
            this.SchemaChanged);
        this.Tables.CollectionChanged += schemaChangedHandler;
        this.Relations.CollectionChanged += schemaChangedHandler;
    }
    
    protected JobsDS(SerializationInfo info, StreamingContext context) {
        string strSchema = ((string)(info.GetValue("XmlSchema",
          typeof(string))));
        if ((strSchema != null)) {
            DataSet ds = new DataSet();
            ds.ReadXmlSchema(new XmlTextReader(new
               System.IO.StringReader(strSchema)));
            if ((ds.Tables["jobs"] != null)) {
            this.Tables.Add(new jobsDataTable(ds.Tables["jobs"]));
            }
            this.DataSetName = ds.DataSetName;
            this.Prefix = ds.Prefix;
            this.Namespace = ds.Namespace;
            this.Locale = ds.Locale;
            this.CaseSensitive = ds.CaseSensitive;
            this.EnforceConstraints = ds.EnforceConstraints;
            this.Merge(ds, false, System.Data.MissingSchemaAction.Add);
            this.InitVars();
        }
        else {
            this.InitClass();
        }
        this.GetSerializationData(info, context);
        System.ComponentModel.CollectionChangeEventHandler
          schemaChangedHandler = new 
            System.ComponentModel.CollectionChangeEventHandler(
              this.SchemaChanged);
        this.Tables.CollectionChanged += schemaChangedHandler;
        this.Relations.CollectionChanged += schemaChangedHandler;
    }
    
    [System.ComponentModel.Browsable(false)]
    [System.ComponentModel.DesignerSerializationVisibilityAttribute(
     System.ComponentModel.DesignerSerializationVisibility.Content)]
    public jobsDataTable jobs {
        get {
            return this.tablejobs;
        }
    }
    
    public override DataSet Clone() {
        JobsDS cln = ((JobsDS)(base.Clone()));
        cln.InitVars();
        return cln;
    }
    
    protected override bool ShouldSerializeTables() {
        return false;
    }
    
    protected override bool ShouldSerializeRelations() {
        return false;
    }
    
    protected override void ReadXmlSerializable(XmlReader reader) {
        this.Reset();
        DataSet ds = new DataSet();
        ds.ReadXml(reader);
        if ((ds.Tables["jobs"] != null)) {
            this.Tables.Add(new jobsDataTable(ds.Tables["jobs"]));
        }
        this.DataSetName = ds.DataSetName;
        this.Prefix = ds.Prefix;
        this.Namespace = ds.Namespace;
        this.Locale = ds.Locale;
        this.CaseSensitive = ds.CaseSensitive;
        this.EnforceConstraints = ds.EnforceConstraints;
        this.Merge(ds, false, System.Data.MissingSchemaAction.Add);
        this.InitVars();
    }
    
    protected override System.Xml.Schema.XmlSchema
      GetSchemaSerializable() {
        System.IO.MemoryStream stream = new System.IO.MemoryStream();
        this.WriteXmlSchema(new XmlTextWriter(stream, null));
        stream.Position = 0;
        return System.Xml.Schema.XmlSchema.Read(new
          XmlTextReader(stream), null);
    }
    
    internal void InitVars() {
        this.tablejobs = ((jobsDataTable)(this.Tables["jobs"]));
        if ((this.tablejobs != null)) {
            this.tablejobs.InitVars();
        }
    }
    
    private void InitClass() {
        this.DataSetName = "JobsDS";
        this.Prefix = "";
        this.Namespace = "";
        this.Locale = new System.Globalization.CultureInfo
             ("en-US");
        this.CaseSensitive = false;
        this.EnforceConstraints = true;
        this.tablejobs = new jobsDataTable();
        this.Tables.Add(this.tablejobs);
    }
    
    private bool ShouldSerializejobs() {
        return false;
    }
    
    private void SchemaChanged(object sender,
     System.ComponentModel.CollectionChangeEventArgs e) {
        if ((e.Action ==
     System.ComponentModel.CollectionChangeAction.Remove)) {
            this.InitVars();
        }
    }
    
    public delegate void jobsRowChangeEventHandler(object sender,
      jobsRowChangeEvent e);
    
    [System.Diagnostics.DebuggerStepThrough()]
    public class jobsDataTable : DataTable,
                  System.Collections.IEnumerable {
        
        private DataColumn columnjob_id;
        
        private DataColumn columnjob_desc;
        
        private DataColumn columnmin_lvl;
        
        private DataColumn columnmax_lvl;
        
        internal jobsDataTable() : 
                base("jobs") {
            this.InitClass();
        }
        
        internal jobsDataTable(DataTable table) : 
                base(table.TableName) {
            if ((table.CaseSensitive != table.DataSet.CaseSensitive)) {
                this.CaseSensitive = table.CaseSensitive;
            }
            if ((table.Locale.ToString() !=
              table.DataSet.Locale.ToString())) {
                this.Locale = table.Locale;
            }
            if ((table.Namespace != table.DataSet.Namespace)) {
                this.Namespace = table.Namespace;
            }
            this.Prefix = table.Prefix;
            this.MinimumCapacity = table.MinimumCapacity;
            this.DisplayExpression = table.DisplayExpression;
        }
        
        [System.ComponentModel.Browsable(false)]
        public int Count {
            get {
                return this.Rows.Count;
            }
        }
        
        internal DataColumn job_idColumn _
            get {
                return this.columnjob_id;
            }
        }
        
        internal DataColumn job_descColumn {
                return this.columnjob_desc;
            }
        }
        
        internal DataColumn min_lvlColumn {
            get {
                return this.columnmin_lvl;
            }
        }
        
        internal DataColumn max_lvlColumn {
            get {
                return this.columnmax_lvl;
            }
        }
        
        public jobsRow this[int index] {
            get {
                return ((jobsRow)(this.Rows[index]));
            }
        }
        
        public event jobsRowChangeEventHandler jobsRowChanged;
        
        public event jobsRowChangeEventHandler jobsRowChanging;
        
        public event jobsRowChangeEventHandler jobsRowDeleted;
        
        public event jobsRowChangeEventHandler jobsRowDeleting;
        
        public void AddjobsRow(jobsRow row)
            this.Rows.Add(row);
        }
        
        public jobsRow AddjobsRow(string job_desc, System.Byte min_lvl,
          System.Byte max_lvl) {
            jobsRow rowjobsRow = ((jobsRow)(this.NewRow()));
            rowjobsRow.ItemArray = new object[] {
                    null,
                    job_desc,
                    min_lvl,
                    max_lvl};
            this.Rows.Add(rowjobsRow);
            return rowjobsRow;
        }
        
        public jobsRow FindByjob_id(short job_id) {
            return ((jobsRow)(this.Rows.Find(new object[] {
                        job_id})));
        }
        
        public System.Collections.IEnumerator GetEnumerator() {
            return this.Rows.GetEnumerator();
        }
        
        public override DataTable Clone() 
          jobsDataTable cln = ((jobsDataTable)(base.Clone()));
            cln.InitVars();
            return cln;
        }
        
        protected override DataTable CreateInstance() {
            return new jobsDataTable();
        }
        
        internal void InitVars() {
            this.columnjob_id = this.Columns["job_id"];
            this.columnjob_desc = this.Columns["job_desc"];
            this.columnmin_lvl = this.Columns["min_lvl"];
            this.columnmax_lvl = this.Columns["max_lvl"];
        }
        
        private void InitClass() {
            this.columnjob_id = new DataColumn("job_id", typeof(short),
               null, System.Data.MappingType.Element);
            this.Columns.Add(this.columnjob_id);
            this.columnjob_desc = new DataColumn("job_desc", 
               typeof(string), null, System.Data.MappingType.Element);
            this.Columns.Add(this.columnjob_desc);
            this.columnmin_lvl = new DataColumn("min_lvl",
               typeof(System.Byte), null,
               System.Data.MappingType.Element);
            this.Columns.Add(this.columnmin_lvl);
            this.columnmax_lvl = new DataColumn("max_lvl",
              typeof(System.Byte), null,
              System.Data.MappingType.Element);
            this.Columns.Add(this.columnmax_lvl);
            this.Constraints.Add(new UniqueConstraint
              ("Constraint1", new DataColumn[] {this.columnjob_id}, true));
            this.columnjob_id.AutoIncrement = true;
            this.columnjob_id.AllowDBNull = false;
            this.columnjob_id.ReadOnly = true;
            this.columnjob_id.Unique = true;
            this.columnjob_desc.AllowDBNull = false;
            this.columnjob_desc.MaxLength = 50;
            this.columnmin_lvl.AllowDBNull = false;
            this.columnmax_lvl.AllowDBNull = false;
        }
        
        public jobsRow NewjobsRow() {
            return ((jobsRow)(this.NewRow()));
        }
        
        protected override DataRow NewRowFromBuilder(
          DataRowBuilder builder) {
            return new jobsRow(builder);
        }
        
        protected override System.Type GetRowType() {
            return typeof(jobsRow);
        }
        
        protected override void OnRowChanged(
          DataRowChangeEventArgs e) 
        {
            base.OnRowChanged(e);
            if ((this.jobsRowChanged != null)) {
                this.jobsRowChanged(this, 
                  new jobsRowChangeEvent(
                   ((jobsRow)(e.Row)), e.Action));
            }
        }
        
        protected override void OnRowChanging(DataRowChangeEventArgs e) 
        {
            base.OnRowChanging(e);
            if ((this.jobsRowChanging != null)) {
                this.jobsRowChanging(this, 
                  new jobsRowChangeEvent(
                    ((jobsRow)(e.Row)), e.Action));
            }
        }
        
        protected override void OnRowDeleted(DataRowChangeEventArgs e) {
            base.OnRowDeleted(e);
            if ((this.jobsRowDeleted != null)) {
                this.jobsRowDeleted(this, 
                  new jobsRowChangeEvent(
                    ((jobsRow)(e.Row)), e.Action));
            }
        }
        
        protected override void OnRowDeleting(DataRowChangeEventArgs e)  
            base.OnRowDeleting(e);
            if ((this.jobsRowDeleting != null)) {
                this.jobsRowDeleting(this, 
                  new jobsRowChangeEvent(
                    ((jobsRow)(e.Row)), e.Action));
            }
        }
        
        public void RemovejobsRow(jobsRow row) {
            this.Rows.Remove(row);
        }
    }
    
    [System.Diagnostics.DebuggerStepThrough()]
    public class jobsRow : DataRow _par         
        private jobsDataTable tablejobs;
        
        internal jobsRow(DataRowBuilder rb) : base(rb) {
            this.tablejobs = ((jobsDataTable)(this.Table));
        }
        
        public short job_id {
            get {
                return ((short)(this[this.tablejobs.job_idColumn]));
            }
            set {
                this[this.tablejobs.job_idColumn] = value;
            }
        }
        
        public string job_desc {
            get {
                return ((string)(this[this.tablejobs.job_descColumn]));
            }
            set {
                this[this.tablejobs.job_descColumn] = value;
            }
        }
        
        public System.Byte min_lvl 
            get {
              return ((System.Byte)
                (this[this.tablejobs.min_lvlColumn]));
            }
            set {
                this[this.tablejobs.min_lvlColumn] = value;
            }
        }
        
        public System.Byte max_lvl 
            get {
               return ((System.Byte)
                 (this[this.tablejobs.max_lvlColumn]));
            }
            set {
                this[this.tablejobs.max_lvlColumn] = value;
            }
        }
    }
    
    [System.Diagnostics.DebuggerStepThrough()]
    public class jobsRowChangeEvent : EventArgs {
        
        private jobsRow eventRow;
        
        private DataRowAction eventAction;
        
        public jobsRowChangeEvent(jobsRow row, DataRowAction action) {
            this.eventRow = row;
            this.eventAction = action;
        }
        
        public jobsRow Row {
            get {
                return this.eventRow;
            }
        }
        
        public DataRowAction Action {
            get {
                return this.eventAction;
            }
        }
    }
}

The typed DataSet accomplishes strong typing by generating a class MyDS, which derives from DataSet (1). The name of the subclass of the DataSet class is equal to DataSet.DataSetName in the original DataSet that produced the XML schema. Four public nested classes are exposed:

  • MyDS.MyTabDataTable:DataTable, IEnumerable

  • MyDS.MyTabRow:DataRow

  • MyDS.MyTabRowChangeEvent:EventArgs

  • MyDS.MyTabRowChangeEventHandler

where

  • MyDS is the DataSet.DataSetName

  • MyTab is the DataTable.TableName

  • MyTabRow is DataTable.TableName + Row

MyDS.MyTabDataTable has a series of private DataColumn members; one data member per column is the table or resultset. There are getters for these, but they are marked internal because you are not allowed to add or delete DataColumns at runtime. There are also four typed delegates for Changing, Changed, Deleting, and Deleted rows.

The typed DataTable has the following methods:

  • An Indexer for Rows and a GetEnumerator method.

  • Two add methods, both called AddMyTabRow but each used a little differently. AddMyTabRow(row), which takes a Row, is used with NewMyTabRow, an empty typed row. AddMyTabRow(n1,n2,n3)takes N parms, where N is the number of columns in the table and MyTab is a placeholder. For example, if the table name were equal to Jobs, the method name would be AddJobsRow.

  • RemoveMyTabRow, a delete method.

The DataColumns are created and added to the DataTable in the DataTable's InitClass method. If metadata is available, it is also filled in at that time. If there is a primary key or unique column, there is a method called FindBykeycolname that uses the primary key as input.

The MyDSRow class exposes columns as public properties. If the column is nullable, there are two predefined helper functions—IsColumnnameNull and SetColumnnameNull—where Columnname is a placeholder for the name of the column.

To delete a DataRow provided by strongly typed DataSets, you would use the convenience method DataRowCollection.Remove rather than Data-Row.Delete. But the two methods have different semantics. The difference between the two is that calling DataRowCollection.Remove is the same as calling DataRow.Delete followed by AcceptChanges. If you use Remove and then use the DataSet to update a database through a DataAdapter, the rows that you deleted in the DataSet using Remove will not be deleted in the database. If this is the desired behavior, you should use DataRow.Delete instead of the convenience RemoveMyTabRow method.

A strongly typed DataSet can also contain more than one table. If you have tables with parent-child relationships—specified by the existence of a DataRelation in the DataSet's Relations collection—some additional information and methods are generated. When the DataSet contains a Relation, the following things happen:

  • The PrimaryKey property is added to DataColumn properties for the parent table, a ForeignKeyConstraint is added for the child table, and DataRelation is added. If the DataSet's Nested property was set in the original schema, it is preserved in the typed DataSet.

  • ChildTabRow has a property of type ParentTabRow. A property's get method calls GetParentRow, and the setter calls SetParent.

  • ParentRow has a method, GetChildTabRow, that returns an array of typed child rows by calling GetChildRows.

where

  • ParentTab is the DataTable.TableName of the parent table.

  • ChildTab is the DataTable.TableName of the child table.

Finally, the strongly typed DataSet has certain methods and a property that are related to XML persistence. These override the DataSet's methods.

  • A protected constructor takes a SerializationInfo info and a StreamingContext context. This constructor calls InitClass before calling GetSerializationData. This is a requirement when you implement ISerializable.

  • ReadXmlSerializable simply calls the base class's ReadXml method.

  • GetSchemaSerializable calls WriteXmlSchema to write the schema to an XmlTextWriter. Then it reads it back into a System.Xml.Schema.XmlSchema. This is similar to the code in the base class (DataSet).

  • The properties ShouldSerializeTables and ShouldSerialize-Relations, and an additional property called ShouldSerialize[MyTable], return false.

The example in Listing 7–25 uses every method of a one-DataTable typed DataSet and a hierarchical typed DataSet with a parent-child relationship. Typed DataSets can also be used as ordinary DataSets, with a corresponding loss of compile-type syntax checking.

Listing 7–25 Using a Typed DataSet

using System;
using System.Data;
using System.Data.SqlClient;

namespace UseDataSet
{
  class Class1
  {
    static void Main(string[] args)
      {
        Class1 c = new Class1();
        c.instanceMain();
      }

      void instanceMain()
      {
        UseJobsWithDBMS();
        UseJobsDS();
        UseAuTitleDS();
      }

      void UseJobsWithDBMS()
      {
        try 
        {
          JobsDS j = new JobsDS();
          SqlDataAdapter da = new SqlDataAdapter(
           "select * from jobs", 
           "server=localhost;uid=sa;database=pubs");

          SqlCommandBuilder bld = new SqlCommandBuilder(da);
          da.Fill(j.jobs);
          Console.WriteLine(j.jobs.Rows.Count);

          JobsDS.jobsRow found_row = j.jobs.FindByjob_id(156);
          Console.WriteLine(j.jobs.Rows.Count);

          //j.jobs.RemovejobsRow(found_row);
          found_row.Delete();
          Console.WriteLine(j.jobs.Rows.Count);
          da.Update(j.jobs);
        }
        catch (Exception e)
        {
          Console.WriteLine(e.Message);
        }
      }

      protected void T_Changing(object sender, 
        JobsDS.jobsRowChangeEvent e) 
      { 
        if (e.Row.RowState == DataRowState.Deleted)
          Console.WriteLine("Row Changing: Action {0}, State {1}",
            e.Action,  e.Row.RowState);
        else
          Console.WriteLine("Row Changing: {0} id = {1}, State {2}", 
            e.Action, e.Row[0], e.Row.RowState);
      }

      protected void T_Changed(object sender, 
        JobsDS.jobsRowChangeEvent e) 
      { 
        if (e.Row.RowState == DataRowState.Detached)
          Console.WriteLine("Row Changed: Action {0}, State {1}",
            e.Action,  e.Row.RowState);
        else
          Console.WriteLine("Row Changed: {0} id = {1}, State {2}", 
            e.Action, e.Row[0], e.Row.RowState);
      }

      protected void T_Deleting(object sender, 
        JobsDS.jobsRowChangeEvent e) 
      { 
        Console.WriteLine("Row Deleting: {0} id = {1}, State {2}", 
          e.Action, e.Row[0], e.Row.RowState);
      }

      protected void T_Deleted(object sender, 
        JobsDS.jobsRowChangeEvent e) 
      { 
        Console.WriteLine("Row Deleted: Action {0}, State {1}", 
          e.Action, e.Row.RowState);
      }

      void UseJobsDS()
      {
        // 1. One public class JobsDS
        // 2. Four public nested classes:
        //    JobsDS.jobsDataTable;
        //    JobsDS.jobsRow;
        //    JobsDS.jobsRowChangeEvent;
        //    JobsDS.jobsRowChangeEventHandler;

        // Generates one named high-level type
        // the DataSet
        JobsDS j = new JobsDS();                      
        Console.WriteLine(j.DataSetName);                              

        // event handlers
        j.jobs.jobsRowChanging += 
          new JobsDS.jobsRowChangeEventHandler(T_Changing);
        j.jobs.jobsRowChanged += 
          new JobsDS.jobsRowChangeEventHandler(T_Changed);
        j.jobs.jobsRowDeleting += 
          new JobsDS.jobsRowChangeEventHandler(T_Deleting);
        j.jobs.jobsRowDeleted += 
          new JobsDS.jobsRowChangeEventHandler(T_Deleted);

        // The DataSet has a single new property named "jobs"
        // It's also a public nested class
        JobsDS.jobsDataTable t = j.jobs;
        Console.WriteLine(j.jobs.TableName);
        
        // add a row
        //j.jobs.AddjobsRow(99, "new job", 20, 20);

        // when you have metadata, it's smarter about this
        // you can't add the identity column
        j.jobs.AddjobsRow("new job", 20, 20);

        // or add a row
        // through the jobsRow public nested class
        JobsDS.jobsRow r = j.jobs.NewjobsRow();

        // convenience columns
        //r.job_id = 100;
        r.job_desc = "job 100";
        r.max_lvl = 90;
        r.min_lvl = 89;

        j.jobs.AddjobsRow(r);

        // convenience IsNull functions
        // only if it can be null
        //if (r.Isjob_descNull() == true)
        //  Console.WriteLine("desc is null");

        // and SetNull functions
        //r.Setjob_idNull();

        // jobs exposes a public property Count == table.Rows.Count
        Console.WriteLine("row count is " + j.jobs.Count);

        // convenience find function
        JobsDS.jobsRow found_row = j.jobs.FindByjob_id(1)
        Console.WriteLine(j.jobs.Rows.Count);

        // strongly typed
        //j.jobs.RemovejobsRow(r);
        j.jobs.RemovejobsRow(found_row);
        Console.WriteLine(j.jobs.Rows.Count);

        // 4 DataColumns as members.
        //j.jobs.job_idColumn;
        //j.jobs.job_descColumn;
        //j.jobs.max_lvlColumn;
        //j.jobs.min_lvlColumn;
        if (j.jobs.job_idColumn.ReadOnly == true)
          Console.WriteLine("its read only");
        Console.WriteLine(j.jobs[0].job_desc);
        
        // change the first column
        // this would fail, column is readonly
        //j.jobs[0].job_id = 98;
        j.jobs[0].job_desc = "new description";
        j.AcceptChanges();

        j.WriteXmlSchema("theschema.xsd");
        j.WriteXml("thedocument.xml");

        JobsDS j2 = new JobsDS();

        // fails, the typed DataSet already contains the typed table.
        //j2.ReadXmlSchema("jobsds.xsd");
        j2.ReadXml("jobsds.xml");
      }

      void UseAuTitleDS()
      {
        try 
        {
          SqlDataAdapter da = new SqlDataAdapter(
            "select * from authors;select * from titleauthor",
            "server=localhost;uid=sa;database=pubs");

          AuTitleDS om = new AuTitleDS();

          // we still must map these because the 
          // mapping is on the DataAdapter
          da.TableMappings.Add("Table", "authors");
          da.TableMappings.Add("Table1", "titleauthors"); 
          da.Fill(om);
          Console.WriteLine("{0} tables", om.Tables.Count);

          AuTitleDS.authorsRow r = om.authors[0];

          // get array of children
          AuTitleDS.titleauthorsRow[] cr = r.GettitleauthorsRows();
          foreach (AuTitleDS.titleauthorsRow tr in cr)
          {
            Console.WriteLine("author {0}, title {1}", 
                              tr.au_id, tr.title_id);
            AuTitleDS.authorsRow ar = tr.authorsRow;
            Console.WriteLine("author {0} is the parent", ar.au_id);
          }
        }
        catch (Exception e)
        {
          Console.WriteLine(e.Message);
        }
      }
    }
}

Although strongly typed DataSets are produced using the names in the schema, you can refine the naming process by using certain schema annotations. These attributes are specified on the element declaration that equates to the table. The annotations are as follows:

  • typedName: Name of an object referring to a row

  • typedPlural: Name of an object referring to a table

  • typedParent: Name of a parent object in a parent-child relationship

  • typedChild: Name of a child object in a parent-child relationship

There is also an annotation, nullValue, that refers to special handling in a strongly typed DataSet when the value in the underlying table is DBNull.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020