Home > Articles > Programming > Windows Programming

Like this article? We recommend

DataSet Code Examples

Now let's take a look at some code samples, both from the server side and from the client side. First we'll address the server side. In Listing 1, you find some code for fetching data from the database with help from a stored procedure.

Listing 1: Code for Filling a DataSet

Dim aCommand As New SqlCommand _
(SprocOrder_FetchWithLines, _GetClosedConnection)
aCommand.CommandType = _
CommandType.StoredProcedure
aCommand.Parameters.Add _
("@id", SqlDbType.Int).Value = id

    Dim anAdapter As New SqlDataAdapter(aCommand)

    anAdapter.TableMappings.Add("Table", "Orders")
    anAdapter.TableMappings.Add _
  ("Table1", "OrderLines")

  anAdapter.TableMappings _
  (OrderTables.Orders).ColumnMappings.Add _
  ("Customer_Id", "CustomerId")
    anAdapter.TableMappings _
  (OrderTables.OrderLines).ColumnMappings.Add _
      ("Orders_Id", "OrderId")
    anAdapter.TableMappings _
  (OrderTables.Orders).ColumnMappings.Add _
      ("Product_Id", "ProductId")

    anAdapter.Fill(dataSet)

Note the basic pattern shown in Listing 1. First a Command is set up. Then comes a DataAdapter, and, finally, Fill is called on the DataAdapter.

NOTE

The code in Listing 1 doesn't show how the DataSet is instantiated. This is because the code in Listing 1 is from a utility method that can be used for filling both typed and untyped DataSets. For that to work, the DataSet is instantiated as a DataSet or an OrderDataSet, for example, outside of the utility method and is sent as a parameter.

Quite a lot of the code in Listing 1 relates to mappings. First is some mapping code for giving the first DataTable the Orders name and then for giving the second DataTable the OrderLines name. For typed DataSets, this is important: Without this, you will end up with four DataTables in the DataSet instead of two. For untyped DataSets, this is important only for creating meaningful names for the DataTables.

The second mapping section is for changing some of the column names used in the stored procedure. Again, for the typed DataSet, this is important, but for the untyped DataSet, this is merely for convenience.

Now let's look at some code from the client side. To browse the information in the DataSet, we could use the code in Listing 2. Note that here I'm browsing a DataSet with two resultsets (or, rather, DataTables).

Listing 2: Code for Browsing a DataSet

Dim anOrderDS As DataSet = _
_service.FetchOrderAndLines(_GetRandomId())

Dim anOrder As DataRow = _
anOrderDS.Tables(OrderTables.Orders).Rows(0)
_id = DirectCast(anOrder(OrderColumns.Id), _
Integer)
_customerId = DirectCast _
(anOrder(OrderColumns.CustomerId), Integer)
_orderDate = DirectCast _
(anOrder(OrderColumns.OrderDate), Date)

    Dim anOrderLine As DataRow
 For Each anOrderLine In anOrderDS.Tables _
 (OrderTables.OrderLines).Rows
_productId = DirectCast(anOrderLine _
(OrderLineColumns.ProductId), Integer)
_priceForEach = CType(anOrderLine _
 (OrderLineColumns.PriceForEach), Decimal)
_noOfItems = DirectCast(anOrderLine _
 (OrderLineColumns.NoOfItems), Integer)
_comment = DirectCast(anOrderLine _
 (OrderLineColumns.Comment), String)
    Next

NOTE

You might wonder about the idea of running a loop for the order lines and then just pushing the value of each column of each order line to a private variable, such as _productId. I do this so that the test runs end to end, all the way from the database to variables in the client. Therefore, I want to touch all columns in all rows of the data container.

Note in Listing 2 that I am referring to DataTables and DataColumns with enumerations. This is to make the code more readable than when magic integers are used and more efficient than when strings are used.

Let's compare the browse code for an untyped DataSet (just shown) with similar code for a typed DataSet. The version for the typed DataSet is found in Listing 3.

Listing 3: Code for Browsing a Typed DataSet

Dim anOrderDs As OrderDs = _
_service.FetchOrderAndLines(_GetRandomId())
Dim anOrder As OrderDs.OrdersRow = _
anOrderDs.Orders(0)

    _id = anOrder.Id
    _customerId = anOrder.CustomerId
    _orderDate = anOrder.OrderDate

    Dim anOrderLine As OrderDs.OrderLinesRow
    For Each anOrderLine In anOrderDs.OrderLines
      _productId = anOrderLine.ProductId
      _priceForEach = anOrderLine.PriceForEach
      _noOfItems = anOrderLine.NoOfItems
      _comment = anOrderLine.Comment
    Next

The code in Listing 3 is clearer and much shorter than the "same" code in Listing 2. This is because the schema is created at compile time, so you don't have to describe it over and over again in your code. Instead of referring to, for example, the generic DataRow class in Listing 2, I'm programming against specific types. I also can skip all the casting and conversions because all columns are in the "correct" data type already. That's definitely a way of reducing code bloat.

DataSet Tests

Time to discuss the test results. As with all the other test cases, there is a service-layer class for each test case. The service-layer classes for the DataSet test cases are shown in Figure 3.

Figure 3Figure 3 One example of a service-layer class.

The service-layer classes inherit, as usual, from MarshalByRefObject. They should be suitable as root classes when used via remoting.

NOTE

Note that the second method in class for the typed DataSet returns OrderDs2. That typed DataSet class has only an OrderLines DataTable. Otherwise, I would have had to use a workaround to avoid getting a constraint error when fetching only OrderLines from the database.

You might think that it would be more appropriate to send just a DataTable instead of a complete DataSet in this case. I will discuss that further in Part 5 of this series.

Result of the Tests

In the first part of the articles series, I gave you a sneak peak regarding the throughput test results of the untyped DataSet. Now it's time to show you the results for all test cases discussed so far.

Once again, I will use DataReader as a baseline. Therefore, I have recalculated all the values so that I get value 1 for DataReader; the rest of the data containers will have a value that is relative to the DataReader value, for easy comparison. The higher the value, the better.

Table 1: Results for the First Test Case: Reading One Row

1 User, in AppDomain

5 Users, in AppDomain

1 User, Cross-Machines

5 Users, Cross-Machines

DataReader

1

1

1

1

Untyped DataSet

0.6

0.6

1.4

1.7

Typed DataSet

0.4

0.5

1

1.1


Table 2: Results for the Second Test Case: Reading Many Rows

1 User, in AppDomain

5 Users, in AppDomain

1 User, Cross-Machines

5 Users, Cross-Machines

DataReader

1

1

1

1

Untyped DataSet

0.6

0.6

6.9

9.7

Typed DataSet

0.5

0.5

6

8.6


Table 3: Results for the Third Test Case: Reading One Master Row and Many Detail Rows

1 User, in AppDomain

5 Users, in AppDomain

1 User, Cross-Machines

5 Users, Cross-Machines

DataReader

1

1

1

1

Untyped DataSet

0.5

0.5

6.1

8.5

Typed DataSet

0.4

0.4

5.1

6.9


As you might guess, the five-users test uses 100% of the CPU because I'm not using any think time. That goes for both the AppDomain test and the cross-machines test.

In the cross-machines test, I should switch to several client machines, but I haven't done that yet. Perhaps I will rerun the tests in Part 5. On the other hand, the server in the five-users, cross-machines test uses approximately 80% of the CPU, so that would be the bottleneck.

This reminds me that I need to mention the test equipment. Because my company is small one (it's just me), I don't have a full-blown lab. Therefore, I have used three ordinary machines:

  • 1.8GHz, 512MB RAM. This serves as everything except the database server in the AppDomain tests. It's the client for the cross-machines tests.

  • 1.7GHz, 512MB RAM. This is the server for the cross-machines tests.

  • 750MHz, 255MB RAM. This is the database server for all the tests.

As you learned earlier, both the Untyped DataSet and the typed DataSet have more overhead than the DataReader in the AppDomain. On the other hand, they perform better than the DataReader in the cross-machines test, especially when several rows are fetched. This is just as expected. It's also expected that the typed DataSet carries more overhead than the untyped DataSet.

But some forthcoming results aren't as you might expect. I'll whet your appetite a bit by telling you that with custom classes for the third test—1 user and cross-machines—I get 16! (That is, it's 16 times more efficient to use custom classes than a DataReader for that specific test.) That is probably not what you expect from all talk about how efficient DataSets are. The untyped DataSet performs almost three times as poorly as custom classes when serialized across machines because DataSets are serialized as XML, even with a binary formatter. Test the code snippet in Listing 4, and open the results file in Notepad to see for yourself.

Listing 4: Code for Serializing a DataSet to a File

Dim fs As IO.FileStream = _
New IO.FileStream("c:\temp\ds.txt", IO.FileMode.Create)

Dim bf As New _
System.Runtime.Serialization. _
Formatters.Binary.BinaryFormatter _
(Nothing, New Runtime.Serialization.StreamingContext _

(Runtime.Serialization.StreamingContextStates.Remoting))

bf.Serialize(fs, anOrderDS)
fs.Close()

NOTE

You can read more about serialization aspects of DataSets in Dino Esposito's article "Binary Serialization of ADO.NET Objects" and in his book Applied XML Programming for Microsoft .NET (Microsoft Press, 2002). There Dino also discusses some workarounds to this problem. I will discuss the test result involved when using a workaround in Part 5 of this series.

Highly Subjective Results

It's time to add some grades for untyped and typed DataSets to my list of "highly subject results." In Table 4, you will find that I have assigned some grades according to the qualities discussed at the beginning of the article. A score of 5 is excellent, and a score of 1 is poor.

Table 4: Grades According to Qualities

 

Performance in AppDomain/Cross-Machines

Scalability in AppDomain/Cross-Machines

Productivity

Maintainability

Interoperability

DataReader

5/1

4/1

2

1

1

DataSet

3/3

3/3

4

3

4

Typed DataSet

2/2

2/2

5

4

5


I'd like to say a few words about each quality grade next.

Performance

Unlike the DataReader, both types of DataSets are marshalled by value. Therefore, performance is okay cross-machines, too.

Scalability

As I said last time, in this specific test I think performance and scalability go hand in hand, as those qualities were defined for this series of articles. It's important to note that DataSets won't hold open connections against the database, so using them entails less risk of killing scalability from holding on to connections too long.

Productivity

DataSets are great for productivity because you get a lot of functionality built in, debugged, and ready to use. Productivity is especially good for typed DataSets because there is a lot of design-time support for them in Visual Studio .NET.

In my opinion, the DataSet is very much about rapid application development (RAD) and does a good job regarding that.

Maintainability

I believe that maintainability will be pretty good for both types of DataSets. It's especially good for the typed DataSet because you have a strong contract against your code accessing it. On the other hand, I really like the idea of keeping the behavior together with the data, as with classic object-oriented solutions, thereby making it possible to get a very high degree of encapsulation. DataSets are useful for a more data-centric or document-centric approach so that you can let the behavior act on the data in the DataSets. This works very well, of course, but, in my opinion, in many situations long-term maintainability suffers.

Also worth mentioning is the loosely coupled model that typed DataSets use. That is, with an event-based model, you can use a specific typed DataSet in many situations, using different rules for each situation. You put the rules in event procedures in other classes instead of within the typed DataSet itself.

Interoperability

Finally, interoperability is pretty good for both types of DataSets. They serialize themselves to XML, but the DataSet also has the built-in possibility of a WriteXml() method that can be used to get a format other than the diffgram format that you get from the ordinary serialization of DataSets.

I decided to give the typed DataSet a score of 5 instead of 4 for interoperability because the XSD means a stronger contract with the client. In my opinion, that is desirable when it comes to interoperability.

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