Blue Theme Orange Theme Green Theme Red Theme
 
Mindcracker MVP Summit 2012
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » ADO.NET & Database » DataSet in C#

DataSet in C#

The ADO.NET DataSet is a data construct that can contain several relational rowsets, the relations that link those rowsets, and the metadata for each rowset. The DataSet also tracks which fields have changed, their new values and their original values, and can store custom information in its Extended Properties collection. The DataSet can be exported to XML or created from an XML document, thus enabling increased interoperability between applications.

Author Rank :
Page Views : 19324
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
DevExpress Free UI Controls
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 



The huge mainstream of applications built today involve data manipulation in some way-whether it be retrieval, storage, change, translation, verification, or transportation. For an application to be scalable and allow other apps to interact with it, the app will need a common mechanism to pass the data around. Ideally, the vehicle that transports the data should contain the base data, any related data and metadata, and should be able to track changes to the data. Here's where the ADO.NET DataSet steps in. The ADO.NET DataSet is a data construct that can contain several relational rowsets, the relations that link those rowsets, and the metadata for each rowset. The DataSet also tracks which fields have changed, their new values and their original values, and can store custom information in its Extended Properties collection. The DataSet can be exported to XML or created from an XML document, thus enabling increased interoperability between applications.

When we look at the DataSet object model, we see that it is made up of three collections; Tables, Relations, and ExtendedProperties. These collections make up the relational data structure of the DataSet. The DataSet.Tables property is a DataTableCollection object, which contains zero or more DataTable objects. Each DataTable represents a table of data from the data source. Each DataTable is made p of a Columns collection and a Rows collection, which are zero or more DataColumns or DataRows, in that order.

The Relations property as a DataRelationCollection object, which contains zero or more DataRelation objects. The DataRelation objects define a parent-child relationship between two tables based on foreign key values. On the other hand, The ExtendedProperties property is a PropertyCollection object, which contains zero or more user-defined properties. The ExtendedProperties collection can be used contains zero or more user defined properties. This property collection can be used to store custom data related to the DataSet, such as the time when the DataSet was constructed.

One of the key points to remember about the DataSet is that it doesn't care where it originated. Unlike the ADO 2.x Recordset, the DataSet doesn't track which database or XML document its data came from. In this way, the DataSet is a standalone data store that can be passed from tier to tier in an n-tiered architecture. This Article, we will continue by showing us how to use the DataSet in a .NET-based application to retrieve data, track modifications made by the user, and send the data back to the database.

Using C# .NET, we will show how to retrieve products from the Northwind database from a business services application and load the information in the presentation tier, all using .NET. We will walk through examples of how to use the DataSet to save several rows to the database at one time. The code samples will demonstrate how to send new rows, changed rows, and deleted rows in one trip to the business services tier and then on to the database by using a DataSet.

Working with .NET DataSets

Before start, to understand the DataSet advanced techniques, we first to recognize the DataTable. As a preview and remainder we will be discussing the DataTable class, and understanding how the DataTable works and its role in a data-driven application. Once we have worked with DataTables, we will begin using DataTables in DataSets, and building DataRelations between two DataTables, in the same way we would have a relationship between tow tables in a database. After everything, we will discuss how to cache DataSets for increased performance.

DataSet Constructors (SerializationInfo, StreamingContext)

This member supports the .NET Framework infrastructure and is not intended to be used directly from our code.

public
DataSet();
public
DataSet(
string
dataSetName
);
protected
DataSet(
SerializationInfo info,
StreamingContext context
);


Object Serialization and the SerializationInfo Class

Serialization is the process of converting a graph of objects, into a linear sequence of bytes. That sequence of bytes can be sent elsewhere (for example, to a remote computer) and Deserialized, by this means making a clone in that remote memory of the original graph of objects. The process of serialization is effortless with .NET and its release too. When any class in ActiveX DLL or ActiveX exe is created, there are five property of class that can be set, the last property known as Persistable is what serialization in C#. In C# with common object library, every language supporting .NET architecture known and can use Serialization Feature with the help of RunTime.Serialization Namespace.

When we complete serialization in .NET, the runtime metadata 'knows' all there is to know about each object's layout in memory, its field and property definitions, this makes serialization of objects automatically, without having to write code to serialize each field.

The serialized stream might be encoded using XML, or a compact binary representation. The format is decided by the Formatter object that is called. Pluggable formatters allows the developer to serialize objects in with the two supplied formats (binary and SOAP) or can be created by developers. Serialization can take place with any stream, not just a FileStream also Serialization makes use of several classes, as follows:

  • Formatter - Responsible for writing object data in some specified format to the output stream. This class is also responsible for driving the deserialization operation.

  • ObjectIDGenerator - ObjectIDGenerator generates IDs for objects. It keeps track of objects already 'seen' so that if you ask for the ID of an object, it knows whether to return its existing ID, or generate (and remember) a new ID.

  • ObjectManager - Keeps track of objects as they are being deserialized. In this way, deserialization can query the ObjectManager to know whether a reference to an object, in the serialized stream, refers to an object that has already been deserialized (a backward reference), or to an object that has not yet been deserialized (a forward reference).

Each of these components is 'Pluggable' - the programmer can provide alternatives.

If a class author wishes to take special action when objects of that class are serialized and deserialized, he can choose to implement the ISerializable interface. This allows full control. For example, the author may define his own, custom SerializationInfo, to describe parts of the object, or synthesized fields that capture the object state for serialization. If a class implements ISerializable, that interface will always be called in preference to default serialization. An important note on deserialization is that we return the fields in the same order in which they are returned from Reflection. Reflection makes no guarantee that it will follow metadata ordering.


This class holds all the data needed to serialize or deserialize an object. Attention please; this class cannot be inherited.

public
sealed class SerializationInfo


Any public static members of this type are safe for multithreaded operations. Any instance members are not guaranteed to be thread safe. This class is used by objects with custom serialization behavior. The GetObjectData method on either ISerializable or ISerializationSurrogate populates the SerializationInfo with the name, type, and value of each piece of information it wants to serialize. During deserialization, the appropriate function can extract this information. Objects are added to the SerializationInfo at serialization time using the AddValue methods and extracted from the SerializationInfo at deserialization using the GetValue methods.

The following code example demonstrates the SerializationInfo for custom serialization and deserialization of various values.

using
System;
using
System.IO;
using
System.Runtime.Serialization;
using
System.Runtime.Serialization.Formatters.Binary;
namespace
Testing
{
public class
Test
{
public static void
Main(String[] args)
{
// Creates a new ExampleClass1 object.
ExampleClass1 f = new
ExampleClass1();
// Opens a file and serializes the object into it in binary format.
Stream stream = File.Open("ExampleClass1ExampleClass2.bin", FileMode.Create);
BinaryFormatter bformatter =
new
BinaryFormatter();
formatter.Serialize(stream, f);
stream.Close();
//Clean f.
f = null
;
// Opens file "ExampleClass1ExampleClass2.bin" and deserializes the ExampleClass1
// object from it.
stream = File.Open("ExampleClass1ExampleClass2.bin", FileMode.Open);
bformatter =
new
BinaryFormatter();
f = (ExampleClass1)bformatter.Deserialize(stream);
stream.Close();
}
}
[Serializable()]
public class
ExampleClass1: ISerializable
{
public
ExampleClass2 someObject;
public int
size;
public
String shape;
//Default constructor
public
ExampleClass1()
{
someObject =
new
ExampleClass2();
}
//Deserialization constructor.
public
ExampleClass1 (SerializationInfo info, StreamingContext context)
{
size = (
int)info.GetValue("size", typeof(int
));
shape = (String)info.GetValue("shape",
typeof(string
));
//Allows ExampleClass2 to deserialize itself
someObject = new
ExampleClass2(info, context);
}
//Serialization function.
public void
GetObjectData(SerializationInfo info, StreamingContext
context)
{
info.AddValue("size", size);
info.AddValue("shape", shape);
//Allows ExampleClass2 to serialize itself
someObject.GetObjectData(info, context);
}
}
public class
ExampleClass2
{
public double value
= 3.14159265;
public
ExampleClass2()
{
}
public
ExampleClass2(SerializationInfo info, StreamingContext context)
{
value = (double)info.GetValue("ExampleClass2_value", typeof(double
));
}
public void
GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("ExampleClass2_value",
value
);
{
}


continue article

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
John Hudai Godel
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.