Serializing Data

using System;
using System.Data;
using System.Data.SqlClient;
// Namespaces used for serialization
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization.Formatters.Binary;

namespace SerializeData
{
class Program
{
static void Main(string[] args)
{
string fileName = @"..\..\..\SerializedDataSet";
Stream stream;

string sqlConnectString = "Data Source=(local);" +
"Integrated security=SSPI;Initial Catalog=AdventureWorks;";

string sqlSelect = "SELECT * FROM Production.Product;" +
"SELECT * FROM Production.ProductInventory";

DataSet ds = new DataSet( );
SqlDataAdapter da;

// Fill the Header table in the DataSet
da = new SqlDataAdapter(sqlSelect, sqlConnectString);
da.TableMappings.Add("Table", "Product");
da.TableMappings.Add("Table1", "ProductInventory");
da.FillSchema(ds, SchemaType.Mapped);
da.Fill(ds);

// Relate the Header and Order tables in the DataSet
DataRelation dr = new DataRelation("Product_ProductInventory",
ds.Tables["Product"].Columns["ProductID"],
ds.Tables["ProductInventory"].Columns["ProductID"]);
ds.Relations.Add(dr);

// Serialize using DataSet.WriteXml( )
using (stream = File.Open(fileName + "_1.xml", FileMode.Create,
FileAccess.Write))
{
ds.WriteXml(stream, XmlWriteMode.WriteSchema);
Console.WriteLine(
"DataSet serialized using DataSet.WriteXml( ) to {0}_1.xml",
fileName);
}

// Serialize using XmlSerializer
using (stream = File.Open(fileName + "_2.xml", FileMode.Create,
FileAccess.Write))
{
XmlSerializer xs = new XmlSerializer(typeof(DataSet));
xs.Serialize(stream, ds);
Console.WriteLine(
"DataSet serialized using XmlSerializer to {0}_2.xml",
fileName);
}

// Serialize using SoapFormatter
using (stream = File.Open(fileName + ".soap", FileMode.Create,
FileAccess.Write))
{
SoapFormatter sf = new SoapFormatter( );
sf.Serialize(stream, ds);
Console.WriteLine(
"DataSet serialized using SoapFormatter to {0}.soap",
fileName);
}

// Serialize using BinaryFormatter
using (stream = File.Open(fileName + ".bin", FileMode.Create,
FileAccess.Write))
{
BinaryFormatter bf = new BinaryFormatter( );
bf.Serialize(stream, ds);
Console.WriteLine(
"DataSet serialized using BinaryFormatter to {0}.bin",
fileName);
}

Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
}
}

No comments: