When the application closes,
unfortunately, all the information created while the application was running is
lost. While the first goal of an application is to create one or more lists used
to organize information, probably the essence of an information-based or a
data-based application is to preserve information created when using the
application and be able to retrieve that information the next time the
application runs, without re-creating it.
Of course, there are various ways you can save the
information created in an application. As the DataSet class is equipped with all
the necessary features used to create and manage one or more lists of an
application, it also provides a very high level of saving the information stored
in its lists.
Once a new record has been created or when the lists of the
data set have been populated with information, you can save the changes and
store them to a computer file. By default, the DataSet class is equipped to save its lists as
XML. To support this, it is equipped with the WriteXml() method that is
overloaded with various versions. One of the versions of this method uses the
following syntax:
public void WriteXml(string fileName);
This method takes as argument the name of the new file or
its path. When providing this argument, make sure you add the .xml extension to
the file name. This method does two things: it checks the existence of the file
and it saves it. If the file you provided is not
found in the path, this method creates it and writes the record(s) to it. If the
file exists already, this method opens it, finds its end, and appends the new
data at the end. This makes the method very useful and friendly.
Here is an example of saving a data set using this method:
using System;
using System.IO;
using System.Data;
namespace VideoCollection
{
public static class Program
{
static DataSet dsVideos;
static DataColumn colShelfNumber;
static DataColumn colTitle;
static DataColumn colDirector;
static DataColumn colLength;
static DataColumn colYear;
static DataColumn colRating;
static DataTable tblVideos;
static string strDirectory;
static void CreateCollection()
{
dsVideos = new DataSet("Videos");
tblVideos = new DataTable("Video");
colShelfNumber = new DataColumn("ShelfNumber",
Type.GetType("System.String"));
tblVideos.Columns.Add(colShelfNumber);
colTitle = new DataColumn("Title",
Type.GetType("System.String"));
tblVideos.Columns.Add(colTitle);
colDirector = new DataColumn("Director",
Type.GetType("System.String"));
tblVideos.Columns.Add(colDirector);
colLength = new DataColumn("Length",
Type.GetType("System.String"));
tblVideos.Columns.Add(colLength);
colYear = new DataColumn("Year",
Type.GetType("System.Int16"));
tblVideos.Columns.Add(colYear);
colRating = new DataColumn("Rating",
Type.GetType("System.String"));
tblVideos.Columns.Add(colRating);
dsVideos.Tables.Add(tblVideos);
strDirectory = @"C:\Video Collection";
Directory.CreateDirectory(strDirectory);
dsVideos.WriteXml(strDirectory + @"\videos.xml");
}
static void CreateRecord()
{
DataRow rowVideo = tblVideos.NewRow();
rowVideo[0] = "GT-682";
rowVideo[1] = "A Few Good Men";
rowVideo[2] = "Rob Reiner";
rowVideo[3] = "138 Minutes";
rowVideo[4] = 1992;
rowVideo[5] = "R";
tblVideos.Rows.Add(rowVideo);
dsVideos.WriteXml(strDirectory + @"\videos.xml");
}
static int Main(string[] args)
{
CreateCollection();
CreateRecord();
return 0;
}
}
}
If you want to control whether the file should be created
from scratch, instead of passing the name of the file to this method, first
create a stream using a Stream-derived class such as FileStream.
This allows specifying the necessary options using the FileMode, FileAccess,
and FileShare properties. Once the stream is ready, pass it to the WriteXml()
method because it is also overloaded with the following syntax:
public void WriteXml(Stream stream);
Here is an example:
using System;
using System.IO;
using System.Data;
namespace VideoCollection
{
public static class Program
{
. . . No Change
static void CreateRecord()
{
FileStream fsVideos = new FileStream(strDirectory + @"\videos.xml",
FileMode.Create,
FileAccess.Write);
object[] rowVideo = { "MM-258", "Fatal Attraction", "Adrian Lyne",
"120 Minutes", 1987, "R" };
tblVideos.Rows.Add(rowVideo);
dsVideos.WriteXml(fsVideos);
fsVideos.Close();
}
static int Main(string[] args)
{
CreateCollection();
CreateRecord();
return 0;
}
}
}
If you want the file to be formatted as text, you can use
the following version of the method:
public void WriteXml(TextWriter writer);
If you prefer to use an XmlWriter variable to manage
the file, use the following version of the method:
public void WriteXml(XmlWriter writer);
Obviously to use this method, you must first define an XmlWriter
type of variable.
Practical Learning: Creating a Data Set
|
|
- To create a new class, on the main menu, click Project -> Add Class...
- Set the Name to Inventory and click Add
- Change the file as follows:
using System;
using System.IO;
using System.Xml;
using System.Data;
namespace CollegeParkAutoParts4
{
public class Inventory
{
private DataColumn colPartNumber;
private DataColumn colYear;
private DataColumn colMake;
private DataColumn colModel;
private DataColumn colPartName;
private DataColumn colPartPrice;
private DataColumn colItemNumber;
private DataColumn colItemName;
private DataColumn colItemPrice;
private DataTable tblAutoParts;
private DataTable tblStoreItems;
private DataSet dsStoreItems;
string strDirectory;
string strFilename;
public Inventory()
{
colPartNumber = new DataColumn("PartNumber",
Type.GetType("System.Int32"));
colYear = new DataColumn("Year",
Type.GetType("System.Int32"));
colMake = new DataColumn("Make",
Type.GetType("System.String"));
colModel = new DataColumn("Model",
Type.GetType("System.String"));
colPartName = new DataColumn("PartName",
Type.GetType("System.String"));
colPartPrice = new DataColumn("PartPrice",
Type.GetType("System.Double"));
tblAutoParts = new DataTable("AutoPart");
tblAutoParts.Columns.Add(colPartNumber);
tblAutoParts.Columns.Add(colYear);
tblAutoParts.Columns.Add(colMake);
tblAutoParts.Columns.Add(colModel);
tblAutoParts.Columns.Add(colPartName);
tblAutoParts.Columns.Add(colPartPrice);
tblStoreItems = new DataTable("StoreItem");
colItemNumber = new DataColumn("ItemNumber",
Type.GetType("System.Int32"));
colItemName = new DataColumn("ItemName",
Type.GetType("System.String"));
colItemPrice = new DataColumn("ItemPrice",
Type.GetType("System.Double"));
tblStoreItems .Columns.Add(colItemNumber);
tblStoreItems.Columns.Add(colItemName);
tblStoreItems.Columns.Add(colItemPrice);
dsStoreItems = new DataSet("StoreItems");
dsStoreItems.Tables.Add(tblAutoParts);
dsStoreItems.Tables.Add(tblStoreItems);
strDirectory = @"C:\College Park Auto Parts";
strFilename = strDirectory + "\\" + "StoreItems.xml";
DirectoryInfo dirInfo = new DirectoryInfo(strDirectory);
if (!dirInfo.Exists)
dirInfo.Create();
}
public void CreateStoreItem()
{
int year = 1960;
int iPartNumber = 0, iItemNumber = 0;
double unitPrice = 0.00D;
string strMake = "Unknown", strModel = "Unknown",
strPartName = "N/A", strItemName = "N/A";
int typeOfItem = 0;
char ansAdd = 'n';
if (File.Exists(strFilename))
dsStoreItems.ReadXml(strFilename);
do
{
try
{
Console.WriteLine("What type of item do you want to add");
Console.WriteLine("1. An auto part (for a car or an engine)");
Console.WriteLine("2. Another type of item, " +
"not for a specific car");
Console.WriteLine("0. Stop");
Console.WriteLine("Enter the following pieces of information");
Console.Write("Your Choice: ");
typeOfItem = int.Parse(Console.ReadLine());
if (typeOfItem == 1)
{
Random rndPartNumber = new Random();
iPartNumber = rndPartNumber.Next(100000, 999999);
try
{
Console.Write("Car Year: ");
year = int.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Invalid year");
}
Console.Write("Make (or None if N/A): ");
strMake = Console.ReadLine();
Console.Write("Model (or None if N/A): ");
strModel = Console.ReadLine();
Console.Write("Part Name: ");
strPartName = Console.ReadLine();
try
{
Console.Write("Unit Price: ");
unitPrice = double.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Invalid unit price");
}
Console.WriteLine("\nHere is a summary of " +
"the part to be added");
Console.WriteLine("--------------------------------");
Console.WriteLine("Part Number: {0}", iPartNumber);
Console.WriteLine("Year: {0}", year);
Console.WriteLine("Make: {0}", strMake);
Console.WriteLine("Model: {0}", strModel);
Console.WriteLine("Part Name: {0}", strPartName);
Console.WriteLine("Unit Price: {0:C}", unitPrice);
Console.WriteLine("--------------------------------");
Console.Write("Are you ready to add it " +
"to the database (y/n)? ");
ansAdd = char.Parse(Console.ReadLine());
if ((ansAdd == 'y') || (ansAdd == 'Y'))
{
DataRow part = tblAutoParts.NewRow();
part["PartNumber"] = iPartNumber;
part["Year"] = year;
part["Make"] = strMake;
part["Model"] = strModel;
part["PartName"] = strPartName;
part["PartPrice"] = unitPrice;
tblAutoParts.Rows.Add(part);
dsStoreItems.WriteXml(strFilename);
}
else
Console.WriteLine("The part will not be " +
"added to the database");
}
else if (typeOfItem == 2)
{
Random rndPartNumber = new Random();
iItemNumber = rndPartNumber.Next(100000, 999999);
Console.Write("Item/Description: ");
strItemName = Console.ReadLine();
try
{
Console.Write("Unit Price: ");
unitPrice = double.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Invalid unit price");
}
Console.WriteLine("\nHere is a summary of" +
" the part to be added");
Console.WriteLine("--------------------------------");
Console.WriteLine("Item Number: {0}", iItemNumber);
Console.WriteLine("Name/Descr: {0}", strItemName);
Console.WriteLine("Unit Price: {0:C}", unitPrice);
Console.WriteLine("--------------------------------");
Console.Write("Are you ready to add it " +
"to the database (y/n)? ");
ansAdd = char.Parse(Console.ReadLine());
if ((ansAdd == 'y') || (ansAdd == 'Y'))
{
DataRow item = tblStoreItems.NewRow();
item["ItemNumber"] = iItemNumber;
item["ItemName"] = strItemName;
item["ItemPrice"] = unitPrice;
tblStoreItems.Rows.Add(item);
dsStoreItems.WriteXml(strFilename);
}
else
Console.WriteLine("The part will not be " +
"added to the database");
}
}
catch (FormatException)
{
Console.WriteLine("Invalid Menu Selection");
}
} while (typeOfItem == 1 || typeOfItem == 2);
}
public void ShowInventory()
{
}
}
}
|
- Access the Program.cs file and change it as follows:
using System;
namespace CollegeParkAutoParts4
{
class Program
{
static int Main(string[] args)
{
Inventory item = new Inventory();
item.CreateStoreItem();
Console.WriteLine();
return 0;
}
}
}
|
- Execute the application and create the following items:
What type of item do you want to add
1. An auto part (for a car or an engine)
2. Another type of item, not for a specific car
0. Stop
Enter the following pieces of information
Your Choice: 1
Car Year: 2005
Make (or None if N/A): Acura
Model (or None if N/A): NSX 3.0L V6
Part Name: Oil Filter
Unit Price: 8.85
Here is a summary of the part to be added
--------------------------------
Part Number: 421960
Year: 2005
Make: Acura
Model: NSX 3.0L V6
Part Name: Oil Filter
Unit Price: $8.85
--------------------------------
Are you ready to add it to the database (y/n)? y
What type of item do you want to add
1. An auto part (for a car or an engine)
2. Another type of item, not for a specific car
0. Stop
Enter the following pieces of information
Your Choice: 1
Car Year: 2002
Make (or None if N/A): Audi
Model (or None if N/A): Quattro 1.8L Turbo
Part Name: Clutch Release Bearing
Unit Price: 55.50
Here is a summary of the part to be added
--------------------------------
Part Number: 234374
Year: 2002
Make: Audi
Model: Quattro 1.8L Turbo
Part Name: Clash Bear
Unit Price: $55.50
--------------------------------
Are you ready to add it to the database (y/n)? y
What type of item do you want to add
1. An auto part (for a car or an engine)
2. Another type of item, not for a specific car
0. Stop
Enter the following pieces of information
Your Choice: 1
Car Year: BMW
Invalid year
Make (or None if N/A): BMW
Model (or None if N/A): 325I 2.5L L6
Part Name: Ignition Coil
Unit Price: 60.85
Here is a summary of the part to be added
--------------------------------
Part Number: 899611
Year: 2002
Make: BMW
Model: 325i 2.5L L6
Part Name: Ignition Coil
Unit Price: $60.85
--------------------------------
Are you ready to add it to the database (y/n)? n
The part will not be added to the database
What type of item do you want to add
1. An auto part (for a car or an enfine)
2. Another type of item, not for a specific car
0. Stop
Enter the following pieces of information
Your Choice: 1
Car Year: 2002
Make (or None if N/A): BMW
Model (or None if N/A): 325i 2.5L L6
Part Name: Ignition Coil
Unit Price: 60.85
Here is a summary of the part to be added
--------------------------------
Part Number: 761840
Year: 2002
Make: BMW
Model: 325I 2.5L L6
Part Name: Ignition Coil
Unit Price: $60.85
--------------------------------
Are you ready to add it to the database (y/n)? Y
What type of item do you want to add
1. An auto part (for a car or an engine)
2. Another type of item, not for a specific car
0. Stop
Enter the following pieces of information
Your Choice: 2
Item/Description: Soda 2L Bottle
Unit Price: 1.75
Here is a summary of the part to be added
--------------------------------
Item Number: 894761
Name/Descr: Soda 2L Bottle
Unit Price: $1.75
--------------------------------
Are you ready to add it to the database (y/n)? Y
What type of item do you want to add
1. An auto part (for a car or an engine)
2. Another type of item, not for a specific car
0. Stop
Enter the following pieces of information
Your Choice: 2
Item/Description: 2
Unit Price: 3
Here is a summary of the part to be added
--------------------------------
Item Number: 722464
Name/Descr: 2
Unit Price: $3.00
--------------------------------
Are you ready to add it to the database (y/n)? n
The part will not be added to the database
What type of item do you want to add
1. An auto part (for a car or an engine)
2. Another type of item, not for a specific car
0. Stop
Enter the following pieces of information
Your Choice: 2
Item/Description: STP Gas Treatment 3-Pack
Unit Price: 2.99
Here is a summary of the part to be added
--------------------------------
Item Number: 126066
Name/Descr: STP Gas Treatment 3-Pack
Unit Price: $2.99
--------------------------------
Are you ready to add it to the database (y/n)? Y
What type of item do you want to add
1. An auto part (for a car or an enfine)
2. Another type of item, not for a specific car
0. Stop
Enter the following pieces of information
Your Choice: 0
Press any key to continue . . .
|
- Close the DOS window
- Open the file in a browser to
see the result
To open the data saved from a list, the DataSet class
provides the ReadXml() method that is overloaded with various versions.
One of the versions of this method uses the following syntax:
public XmlReadMode ReadXml(string fileName);
This method takes as argument the name of an existing XML
file or its path. The method opens the file and provides the XML formatting as
it was done when the file was saved. Here is an example of calling this method:
using System;
using System.IO;
using System.Data;
namespace VideoCollection
{
public static class Program
{
static DataSet dsVideos;
static DataColumn colShelfNumber;
static DataColumn colTitle;
static DataColumn colDirector;
static DataColumn colLength;
static DataColumn colYear;
static DataColumn colRating;
static DataTable tblVideos;
static string strDirectory;
static void CreateCollection()
{
dsVideos = new DataSet("Videos");
tblVideos = new DataTable("Video");
colShelfNumber = new DataColumn("ShelfNumber",
Type.GetType("System.String"));
tblVideos.Columns.Add(colShelfNumber);
colTitle = new DataColumn("Title",
Type.GetType("System.String"));
tblVideos.Columns.Add(colTitle);
colDirector = new DataColumn("Director",
Type.GetType("System.String"));
tblVideos.Columns.Add(colDirector);
colLength = new DataColumn("Length",
Type.GetType("System.String"));
tblVideos.Columns.Add(colLength);
colYear = new DataColumn("Year",
Type.GetType("System.Int16"));
tblVideos.Columns.Add(colYear);
colRating = new DataColumn("Rating",
Type.GetType("System.String"));
tblVideos.Columns.Add(colRating);
dsVideos.Tables.Add(tblVideos);
strDirectory = @"C:\Video Collection";
Directory.CreateDirectory(strDirectory);
}
static void CreateRecord()
{
if (File.Exists(strDirectory + @"\videos.xml"))
dsVideos.ReadXml(strDirectory + @"\videos.xml");
object[] arrVideo = { "FD-205", "Her Alibi", "Bruce Beresford",
"94 Minute", 1989, "PG-13" };
DataRow rowVideo = tblVideos.NewRow();
rowVideo.ItemArray = arrVideo;
tblVideos.Rows.Add(rowVideo);
dsVideos.WriteXml(strDirectory + @"\videos.xml");
}
static int Main(string[] args)
{
CreateCollection();
CreateRecord();
return 0;
}
}
}
Although this method can read any XML file,
if you use it to open a file that was saved by someone else or another
application and you want to use it in your application, you should be familiar
with the names of its nodes. If it contains names that are not
"registered" or recognized by your DataSet object, the lists that
compose your application may not be able to read it, not because the list was
not formatted right, but because the lists of your application would be holding
different names.
If the file was saved using a Stream-based class, you can
pass a stream to the method based on the following syntax:
public XmlReadMode ReadXml(Stream stream);
In the same way, the method provides an equivalent version
for the TextWriter and the XmlWriter versions:
public XmlReadMode ReadXml(TextReader reader);
public XmlReadMode ReadXml(XmlReader reader);
To use one of these versions, you must first define a TextWriter
or an XmlReader type of variable.
When retrieving the content of the XML file, if you want it
delivered as text, call the DataSet.GetXml() method. Its syntax is:
public string GetXml();
As you can see, this method returns a String string.
Once a file has been opened, you can explore its content.
The most obvious operation related to opening a data set consists of viewing its
records.
Committing or Rejecting Changes to a List |
|
When a user has created a record, the data set that holds
the information is considered to have been modified because, obviously, it
doesn't have the same information or the same records it had when the
application was launched. You, as the programmer, have the option of accepting the
changes or rejecting them. To accept the changes, call the DataSet.AcceptChanges()
method. Its syntax is:
public void AcceptChanges();
If you don't want the changes to take effect, you can reject
them by calling the DataSet.RejectChanges() method. Its syntax is:
public virtual void RejectChanges();
This method can be called to dismiss whatever changes where
made on the records of the list(s).
|
|