Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

6.2  Generating Typed DataSets

Now that you understand what Typed DataSets are all about, let's create our own. Typed DataSets can be generated in two ways: from within Visual Studio .NET or with the XSD.exe command-line tool. I will start with the Visual Studio .NET solution.

6.2.1  Using Visual Studio .NET to Create a Typed DataSet

This section will walk you through creating a Typed DataSet in Visual Studio. NET. To get started, please create a new Console C# project, as shown in Figure 6.3. Next, in the Solution Explorer add a new item, as shown in Figure 6.4.

Figure 6.3Figure 6.3: Creating a new C# project

Figure 6.4Figure 6.4: Adding a new item

From the Data folder in the Local Project Items, select a new DataSet and name it ADONET.xsd, as shown in Figure 6.5. If you add an XML Schema file instead (they both are .XSD files), the Typed DataSet will not generate. Make sure it is a DataSet. When you finish, the IDE will look something like what is shown in Figure 6.6.

Figure 6.5Figure 6.5: Adding a DataSet


Figure 6.6Figure 6.6: A blank canvas

You probably have noticed already that the Typed DataSet has an extension of .xsd. This is because the source of a Typed DataSet is an XML Schema Document. What the IDE asks you to do is to create a new .XSD file that represents the schema of the DataSet. This will include the schema information we discussed in Chapter 5. The XSD can include table and column names as well as keys, relationships, and constraints.

Now that you have a new Typed DataSet added to your project, you can use either the Server Explorer to add tables to the DataSet or the Toolbox to add elements to the DataSet. Using the Server Explorer to add tables is shown in Figure 6.7.

Figure 6.7Figure 6.7: The Server Explorer

After you have the Server Explorer open to an existing database, you can simply drag and drop the tables you want onto the .XSD file, to produce something that looks like Figure 6.8.

Figure 6.8Figure 6.8: Tables in the .XSD file

At this point, the new Typed DataSet will include two tables, but the tables remain unrelated. Unfortunately Visual Studio .NET does not try to discern all the schema information that may be contained in the database. In order to set the schema information, you will need to add it to the XSD.

We will start by adding a relationship between the Customer and Invoice tables. To do this, drag a new Relation from the Toolbox onto the Customer table, as shown in Figure 6.9. Once you do that, the Edit Relation dialog box appears, as shown in Figure 6.10.

Figure 6.9Figure 6.9: Adding a relationship


Figure 6.10Figure 6.10: The Edit Relation dialog box

The Edit Relation dialog box is where you will provide the specifics of the relationship. You will need to change the child element to the child table (in this case Invoice). Usually the dialog box will correctly select the foreign key field(s). If necessary, you can change the way that the Update rule, Delete rule, and Accept/Reject rule settings affect cascading changes to the DataSet. After you make these changes you should see something similar to what is shown in Figure 6.11.

Figure 6.11Figure 6.11: The completed Edit Relation dialog box

After you click OK, you will see the Relation, as shown in Figure 6.12.

Now that we have our tables and the relationship set up, let's add an expression column to our Customer table. To add an expression column, go to the bottom of the Customer table and add a new row. Name it FullName and look at the properties for the column. Set the expression of the column to:

LastName + ', ' + FirstName

Figure 6.12Figure 6.12: Our tables with a new relationship

Once you have done this, it should look like that shown in Figure 6.13.

Lastly, we need to add a unique constraint on Home Phone to make sure all of our customers' home phone numbers are unique. In the Typed DataSet vernacular, you will need to add a key to that column. Select the column, right-click on it, and select Add Key, as shown in Figure 6.14. This will launch the Edit Key dialog box, shown in Figure 6.15.

Figure 6.13Figure 6.13: Adding an expression column

Figure 6.14Figure 6.14: Selecting Add Key

Figure 6.15Figure 6.15: Naming the key

If you do nothing but name the key and click OK, you've created a unique constraint. There may be cases in which you want to support having a multi-column unique key. To do this you would add fields to the key in the dialog box, as shown in Figure 6.16.

Figure 6.16Figure 6.16: Supporting a multi-column unique key

This unique constraint will force the DataSet to make sure that all HomePhone and BusinessPhone combinations are unique. Congratulations, you now have your Typed DataSet defined.

Before we can see the code that Visual Studio .NET will generate, we need to build the project. After you build the project, your new Typed DataSet will be available for use.

6.2.2  Using XSD.exe to Create a Typed DataSet

Much like creating the class from Visual Studio .NET, Typed DataSets can also be created directly from an XML Schema Document (XSD) using the command-line XSD.exe tool that is included in the .NET Framework SDK. If you are not using Visual Studio .NET or just like your tools to be command-line tools, XSD.exe is for you. If you are using Visual Studio .NET, its built-in support for Typed DataSets is much easier than the tool and produces the same classes.

This tool is used to generate code from XML Schema Documents—both classes derived from the .NET XML classes and those derived from the DataSet family of classes. Before we can start, we will need an XSD document. We can use the DataSet to create one of these for us, as in Listing 6.3.

Listing 6.3: Creating an XSD from a DataSet

...

// Create a DataAdapter for each of the tables we're filling
SqlDataAdapter daCustomers = 
         new SqlDataAdapter("SELECT * FROM CUSTOMER", conn);

// Create your blank DataSet
DataSet dataSet = new DataSet();

// Fill the DataSet with each DataAdapter
daCustomers.Fill(dataSet, "Customers");

// Grab our DataTable for simplicity
DataTable customersTable = dataSet.Tables["Customers"];

// Improve the schema
customersTable.Columns["CustomerID"].ReadOnly = true;
customersTable.Columns["CustomerID"].Unique = true;
customersTable.Columns["LastName"].MaxLength = 50;
customersTable.Columns["LastName"].AllowDBNull = false;
customersTable.Columns["FirstName"].MaxLength = 50;
customersTable.Columns["FirstName"].AllowDBNull = false;
customersTable.Columns["MiddleName"].MaxLength = 50;
customersTable.Columns["State"].DefaultValue = "MA";
customersTable.Columns["State"].MaxLength = 2;
customersTable.Columns["HomePhone"].Unique = true;

// Write out our XSD file to use to generate our 
// typed DataSet
dataSet.WriteXmlSchema(@"c:\CustomerDS.xsd");

Once we run this code, we will have a CustomersDS.xsd file to use with XSD.exe. To generate the class, simply go to the command line and use the XSD.exe tool, as shown in Figure 6.17.

Figure 6.17Figure 6.17: Running the XSD.exe tool from the command line

The most interesting options are:

  • /d specifies to create a schema class that is of type DataSet. For Typed DataSet you will always specify this flag.

  • /l specifies the language in which to generate the classes—CS is C#, VB is VB .NET and JS is Jscript .NET.

  • /n specifies the namespace to create our class in. This flag is optional.

  • /o specifies the output directory. If used, the output directory must already exist; the tool will not create it. If this is not specified, the classes will be created in the current directory.

Now you have your class file to include in your project.

6.2.3  Customizing the Generated Code with Annotations

ADO.NET allows you to control some aspects of the generated code by annotating the XSD that you use to generate the Typed DataSets. You can do this by annotating your XSD with several special attributes. All of these attributes are prefixed with the namespace of codegen. These attributes are:

  • typedName: Specifies the name of an object.

  • typedPlural: Specifies the name of the collection of objects.

  • typedParent: Specifies the name of the parent relationship.

  • typedChildren: Specifies the name of the child relationship.

  • nullValue: Specifies how to handle a DBNull value for a particular row value. When you use this annotation, there are several possible values for the nullValue attribute:

    • Replacement Value: The value to return instead of a null (for example, codegen:nullValue="" will return an empty string instead of a null for a string field).

    • _throw: Throws an exception when the value is accessed and is null (for example, codegen:nullValue=_throw). If the user would use the IsNull properties as part of the Typed DataSet to determine whether the field is null before trying to retrieve it. This is the default behavior if not annotated.

    • _null: Returns a null reference from the field. If a value type is encountered an exception is thrown.

    • _empty: Returns a reference created with an empty constructor. For strings, it returns String.Empty. For value types, an exception is thrown.

These must be added directly to the .XSD file. If you are using Visual Studio .NET, you must go to the XML view of your XSD to add these annotations. These annotations are added to an XSD like so:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema id="AnnotatedTDS"
      targetNamespace="http://tempuri.org/AnnotatedTDS"
      elementFormDefault="qualified"
      attributeFormDefault="qualified"
      xmlns="http://tempuri.org/AnnotatedTDS"
      xmlns:mstns="http://tempuri.org/AnnotatedTDS"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
      xmlns:codegen="urn:schemas-microsoft-com:xml-msprop" >
  <xs:element name="AnnotatedTDS" msdata:IsDataSet="true">
    <xs:complexType>
      <xs:choice maxOccurs="unbounded">
        <xs:element name="Customer"
                    codegen:typedName="OurCustomer"
                    codegen:typedPlural="OurCustomers">
...
              <xs:element name="MiddleName" type="xs:string"
                          minOccurs="0"
                          codegen:nullValue="_empty" />
...
        </xs:element>
        <xs:element name="Invoice"
                    codegen:typedName="TheirInvoice"
                    codegen:typedPlural="TheirInvoices">
...
              <xs:element name="Terms" type="xs:string"
                          minOccurs="0"
                          codegen:nullValue="Net 30" />
...
        </xs:element>
      </xs:choice>
    </xs:complexType>
    <xs:keyref name="CustomerInvoice"
               refer="ADONETKey1"
               msdata:AcceptRejectRule="Cascade"
               msdata:DeleteRule="Cascade"
               msdata:UpdateRule="Cascade"
               codegen:typedChildren="Invoices"
               codegen:typedParent="Customer">
      <xs:selector xpath=".//mstns:Invoice" />
      <xs:field xpath="mstns:CustomerID" />
    </xs:keyref>
...
  </xs:element>
</xs:schema>

Let's walk through this XSD and see where we have put the annotations.

  1. The first thing we needed to do was to add the namespace reference to the schema header. This simply tells the XSD that we have a namespace defined and to allow the attributes.

  2. Next, we make some changes to the Customer Element. typedName changes the name of the Typed DataRow in the DataTable to OurCustomer. When you ask for an individual row from the DataTable, it will return you an instance of the OurCustomer class instead of the default of Customer. typedPlural changes the name of the property on the DataSet that returns the specific DataTable. When retrieving the Customer DataTable, you would call the OurCustomers property.

  3. Next, we added the codegen:nullValue="_empty" to the MiddleName element. This annotated our XSD so that a DBNull in the middle name element should be treated as an empty string in our generated Typed DataSet.

  4. Next, we changed the Invoice element just like we did the Customer element. We renamed the Typed DataRow to TheirInvoice and the property that returns it to TheirInvoices.

  5. Last, we changed the names of each end of our relationship by annotating the keydef tag with typedChildren and typedParent. This changes how each side of the relationship is named. The Customer class will have a method called Invoices (instead of GetInvoiceTable) to navigate down the relationship and the Invoice class will have a method called Customer (instead of GetCustomerTable) to navigate up the relationship.

  • + Share This
  • 🔖 Save To Your Account

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