Serializing Data
Số trang: 5
Loại file: pdf
Dung lượng: 26.78 KB
Lượt xem: 5
Lượt tải: 0
Xem trước 2 trang đầu tiên của tài liệu này:
Thông tin tài liệu:
[ Team LiB ] Recipe 5.4 Serializing Data Problem You need to serialize the contents of a DataSet so that you can store the data on a disk or transfer it across a network. Solution You can serialize a DataSet into XML, binary, or SOAP formats and save the serialized DataSet to a stream (such as a file or network stream).
Nội dung trích xuất từ tài liệu:
Serializing Data [ Team LiB ]Recipe 5.4 Serializing DataProblemYou need to serialize the contents of a DataSet so that you can store the data on a disk ortransfer it across a network.SolutionYou can serialize a DataSet into XML, binary, or SOAP formats and save the serializedDataSet to a stream (such as a file or network stream).The sample code creates a DataSet containing the Orders and Order Details tables fromNorthwind and a relation between the two tables. A file stream is created and the DataSetis serialized to the stream using a specified format.The C# code is shown in Example 5-4.Example 5-4. File: SerializeForm.cs// Namespaces, variables, and constantsusing System;using System.Configuration;using System.Windows.Forms;using System.IO;using System.Data;using System.Data.SqlClient;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary;using System.Runtime.Serialization.Formatters.Soap;using System.Xml.Serialization;// Table name constantsprivate const String ORDERS_TABLE = Orders;private const String ORDERDETAILS_TABLE = OrderDetails;// Relation name constantsprivate const String ORDERS_ORDERDETAILS_RELATION = Orders_OrderDetails_Relation;// Field name constantsprivate const String ORDERID_FIELD = OrderID;private SaveFileDialog sfd;// . . .private void goButton_Click(object sender, System.EventArgs e){ DataSet ds = new DataSet( ); SqlDataAdapter da; // Fill the Order table and add it to the DataSet. da = new SqlDataAdapter(SELECT * FROM Orders, ConfigurationSettings.AppSettings[Sql_ConnectString]); DataTable orderTable = new DataTable(ORDERS_TABLE); da.FillSchema(orderTable, SchemaType.Source); da.Fill(orderTable); ds.Tables.Add(orderTable); // Fill the OrderDetails table and add it to the DataSet. da = new SqlDataAdapter(SELECT * FROM [Order Details], ConfigurationSettings.AppSettings[Sql_ConnectString]); DataTable orderDetailTable = new DataTable(ORDERDETAILS_TABLE); da.FillSchema(orderDetailTable, SchemaType.Source); da.Fill(orderDetailTable); ds.Tables.Add(orderDetailTable); // Create a relation between the tables. ds.Relations.Add(ORDERS_ORDERDETAILS_RELATION, ds.Tables[ORDERS_TABLE].Columns[ORDERID_FIELD], ds.Tables[ORDERDETAILS_TABLE].Columns[ORDERID_FIELD], true); // Create and open the stream for serializing. Stream stream = null; try { stream = File.Open(fileNameTextBox.Text, FileMode.Create, FileAccess.Write); } catch(Exception ex) { MessageBox.Show(ex.Message, Serializing Data, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Serialize. if (xmlWriteRadioButton.Checked) { ds.WriteXml(stream, XmlWriteMode.WriteSchema); } else if (xmlSerializerRadioButton.Checked) { XmlSerializer xs = new XmlSerializer(typeof(DataSet)); xs.Serialize(stream, ds); } else if(soapRadioButton.Checked) { SoapFormatter sf = new SoapFormatter( ); sf.Serialize(stream, ds); } else if(binaryRadioButton.Checked) { BinaryFormatter bf = new BinaryFormatter( ); bf.Serialize(stream, ds); } stream.Close( ); MessageBox.Show(Serialization complete., Serializing Data, MessageBoxButtons.OK, MessageBoxIcon.Information);}private void fileDialogButton_Click(object sender, System.EventArgs e){ // File dialog to save file if(xmlWriteRadioButton.Checked || xmlSerializerRadioButton.Checked) sfd.Filter = XML files (*.xml)|*.xml; else if(soapRadioButton.Checked) sfd.Filter = SOAP files (*.soap)|*.soap; else if(binaryRadioButton.Checked) sfd.Filter = Binary files (*.bin)|*.bin; sfd.Filter += |All files (*.*)|*.*; sfd.FilterIndex = 0; if (sfd.ShowDialog( ) == DialogResult.OK) fileNameTextBox.Text = sfd.FileName;}DiscussionSerialization converts an object into a stream of data that can be transported or saved as afile. Deserialization reconstructs the original object from the file.The most basic data serialization is done by writing the contents of the DataSet object toXML using the WriteXml( ) or GetXml( ) method. The contents are then deserializedwith the ReadXml( ) method. These methods, unlike the others shown in this solution, arelimited to serializing and deserializing DataSet objects and provide little control overserialization format.The XmlSerializer class serializes and deserializes objects into XML classes. It performsshallow serialization: only the read-write property values of the class are serialized, notthe underlying data. The XML stream generated by the XmlSerializer class is compliantwith the World Wide Web Consortium (http://www.w3.org) XML Schema Definition(XSD) language 1.0 recommendations. The XmlSerializer object can serialize to anyobject that inherits from System.IO.Stream. When constructing the XmlSerializer object,you must specify the type of object that can be serialized by the instance.You can also use the XmlSerializer class to serialize an object into a SOAP XML streamthat conforms to Section 5 of the World Wide Web Consortium document SimpleObject Access Protocol (SOAP) 1.1. To do this, use the overloaded constructor thataccepts the XmlTypeMapping argument. For more information, see the topicXmlSerializer Constructor in the MSDN library.The IFormatter interface provides functionality for formatting serialized objects. Theclass to be serialized must be marked with the SerializableAttribute attribute; otherwise, aSerializationException will be raised. A class can implement the ISerializable interface tooverride the default serialization behavior.The System.Runtime.Serialization.Formatter class provides base functionality for theserialization formatters:System.Runtime.Serialization.Formatters.Binary ...
Nội dung trích xuất từ tài liệu:
Serializing Data [ Team LiB ]Recipe 5.4 Serializing DataProblemYou need to serialize the contents of a DataSet so that you can store the data on a disk ortransfer it across a network.SolutionYou can serialize a DataSet into XML, binary, or SOAP formats and save the serializedDataSet to a stream (such as a file or network stream).The sample code creates a DataSet containing the Orders and Order Details tables fromNorthwind and a relation between the two tables. A file stream is created and the DataSetis serialized to the stream using a specified format.The C# code is shown in Example 5-4.Example 5-4. File: SerializeForm.cs// Namespaces, variables, and constantsusing System;using System.Configuration;using System.Windows.Forms;using System.IO;using System.Data;using System.Data.SqlClient;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary;using System.Runtime.Serialization.Formatters.Soap;using System.Xml.Serialization;// Table name constantsprivate const String ORDERS_TABLE = Orders;private const String ORDERDETAILS_TABLE = OrderDetails;// Relation name constantsprivate const String ORDERS_ORDERDETAILS_RELATION = Orders_OrderDetails_Relation;// Field name constantsprivate const String ORDERID_FIELD = OrderID;private SaveFileDialog sfd;// . . .private void goButton_Click(object sender, System.EventArgs e){ DataSet ds = new DataSet( ); SqlDataAdapter da; // Fill the Order table and add it to the DataSet. da = new SqlDataAdapter(SELECT * FROM Orders, ConfigurationSettings.AppSettings[Sql_ConnectString]); DataTable orderTable = new DataTable(ORDERS_TABLE); da.FillSchema(orderTable, SchemaType.Source); da.Fill(orderTable); ds.Tables.Add(orderTable); // Fill the OrderDetails table and add it to the DataSet. da = new SqlDataAdapter(SELECT * FROM [Order Details], ConfigurationSettings.AppSettings[Sql_ConnectString]); DataTable orderDetailTable = new DataTable(ORDERDETAILS_TABLE); da.FillSchema(orderDetailTable, SchemaType.Source); da.Fill(orderDetailTable); ds.Tables.Add(orderDetailTable); // Create a relation between the tables. ds.Relations.Add(ORDERS_ORDERDETAILS_RELATION, ds.Tables[ORDERS_TABLE].Columns[ORDERID_FIELD], ds.Tables[ORDERDETAILS_TABLE].Columns[ORDERID_FIELD], true); // Create and open the stream for serializing. Stream stream = null; try { stream = File.Open(fileNameTextBox.Text, FileMode.Create, FileAccess.Write); } catch(Exception ex) { MessageBox.Show(ex.Message, Serializing Data, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Serialize. if (xmlWriteRadioButton.Checked) { ds.WriteXml(stream, XmlWriteMode.WriteSchema); } else if (xmlSerializerRadioButton.Checked) { XmlSerializer xs = new XmlSerializer(typeof(DataSet)); xs.Serialize(stream, ds); } else if(soapRadioButton.Checked) { SoapFormatter sf = new SoapFormatter( ); sf.Serialize(stream, ds); } else if(binaryRadioButton.Checked) { BinaryFormatter bf = new BinaryFormatter( ); bf.Serialize(stream, ds); } stream.Close( ); MessageBox.Show(Serialization complete., Serializing Data, MessageBoxButtons.OK, MessageBoxIcon.Information);}private void fileDialogButton_Click(object sender, System.EventArgs e){ // File dialog to save file if(xmlWriteRadioButton.Checked || xmlSerializerRadioButton.Checked) sfd.Filter = XML files (*.xml)|*.xml; else if(soapRadioButton.Checked) sfd.Filter = SOAP files (*.soap)|*.soap; else if(binaryRadioButton.Checked) sfd.Filter = Binary files (*.bin)|*.bin; sfd.Filter += |All files (*.*)|*.*; sfd.FilterIndex = 0; if (sfd.ShowDialog( ) == DialogResult.OK) fileNameTextBox.Text = sfd.FileName;}DiscussionSerialization converts an object into a stream of data that can be transported or saved as afile. Deserialization reconstructs the original object from the file.The most basic data serialization is done by writing the contents of the DataSet object toXML using the WriteXml( ) or GetXml( ) method. The contents are then deserializedwith the ReadXml( ) method. These methods, unlike the others shown in this solution, arelimited to serializing and deserializing DataSet objects and provide little control overserialization format.The XmlSerializer class serializes and deserializes objects into XML classes. It performsshallow serialization: only the read-write property values of the class are serialized, notthe underlying data. The XML stream generated by the XmlSerializer class is compliantwith the World Wide Web Consortium (http://www.w3.org) XML Schema Definition(XSD) language 1.0 recommendations. The XmlSerializer object can serialize to anyobject that inherits from System.IO.Stream. When constructing the XmlSerializer object,you must specify the type of object that can be serialized by the instance.You can also use the XmlSerializer class to serialize an object into a SOAP XML streamthat conforms to Section 5 of the World Wide Web Consortium document SimpleObject Access Protocol (SOAP) 1.1. To do this, use the overloaded constructor thataccepts the XmlTypeMapping argument. For more information, see the topicXmlSerializer Constructor in the MSDN library.The IFormatter interface provides functionality for formatting serialized objects. Theclass to be serialized must be marked with the SerializableAttribute attribute; otherwise, aSerializationException will be raised. A class can implement the ISerializable interface tooverride the default serialization behavior.The System.Runtime.Serialization.Formatter class provides base functionality for theserialization formatters:System.Runtime.Serialization.Formatters.Binary ...
Tìm kiếm theo từ khóa liên quan:
công nghệ thông tin kỹ thuật lập trình Oreilly Ado Dot Net Cookbook Ebook-Lib Serializing DataGợi ý tài liệu liên quan:
-
52 trang 430 1 0
-
Top 10 mẹo 'đơn giản nhưng hữu ích' trong nhiếp ảnh
11 trang 314 0 0 -
74 trang 299 0 0
-
96 trang 293 0 0
-
Báo cáo thực tập thực tế: Nghiên cứu và xây dựng website bằng Wordpress
24 trang 289 0 0 -
Đồ án tốt nghiệp: Xây dựng ứng dụng di động android quản lý khách hàng cắt tóc
81 trang 281 0 0 -
EBay - Internet và câu chuyện thần kỳ: Phần 1
143 trang 275 0 0 -
Tài liệu dạy học môn Tin học trong chương trình đào tạo trình độ cao đẳng
348 trang 269 1 0 -
Kỹ thuật lập trình trên Visual Basic 2005
148 trang 265 0 0 -
Tài liệu hướng dẫn sử dụng thư điện tử tài nguyên và môi trường
72 trang 265 0 0