Serializing and Deserializing Objects

   

Now that you have created a serializable object, you are ready to add the code that will perform the actual serialization and deserialization. Create two private member functions within the ObjectSerializationForm class named SaveState and RestoreState. Both functions do not take any parameters, and they both return void.

As you may have guessed, serialization will occur within the SaveState function, and deserialization will take place in the RestoreState. We will concentrate on serialization to begin with. The first step is to create a StateInfo private member variable for the form class. Create a new instance of this class within the constructor of your form class. As mentioned at the beginning of this hour, the form contains two text boxes used to change the value of two variables. These variables correspond to the serializable and nonserializable string properties contained within the StateInfo class. In the event handler named SetSerialized_Click, set the SerializedString property of the StateInfo class to the Text property of the m_tbSerializedString variable. Likewise, set the NonSerializedString property of the StateInfo class to the Text property of the m_tbNonSerializedString member variable, as shown in Listing 24.3.

Within the SaveState member function, save the Size and Location properties of your Windows Form to the corresponding properties within the StateInfo class. Now that the appropriate state information is saved within the StateInfo class, you can serialize that object and save it in binary form on the hard disk. The first step is to create a new BinaryFormatter object. This is the .NET Framework class responsible for performing binary serialization. Next, create a new FileStream object, which will be used for writing the binary stream to a file, as shown on line 35 of Listing 24.3. To perform the actual serialization, call the BinaryFormatter member function Serialize, passing the FileStream object and the StateInfo object as the two parameters. Finally, close the FileStream object by calling the Close member function contained within the FileStream class.

Listing 24.3 Serializing and Deserializing Objects
 1: void Serialize_Click(Object* sender, EventArgs* e)  2: {  3:     SaveState();  4: }  5:  6: void Load_Click(Object* sender, EventArgs* e)  7: {  8:     RestoreState();  9: } 10: 11: void Dump_Click(Object* sender, EventArgs* e) 12: { 13:     m_tbObjectDump->Text = String::Format( "Serialized: {0}\r\n \ 14:         Non-Serialized: {1}", m_pStateInfo-ializedString, 15:         m_pStateInfo->NonSerializedString ); 16: } 17: 18: void SetSerialized_Click(Object* sender, EventArgs* e) 19: { 20:     m_pStateInfo->SerializedString = m_tbSerializedString->Text; 21: } 22: 23: void SetNonSerialized_Click(Object* sender, EventArgs* e) 24: { 25:     m_pStateInfo->NonSerializedString = m_tbNonSerializedString->Text; 26: } 27: 28: void SaveState() 29: { 30:     // save form properties first 31:     m_pStateInfo->Form_Size = this->Size; 32:     m_pStateInfo->Form_Location = this->Location; 33: 34:     IFormatter* formatter = new BinaryFormatter(); 35:     Stream* stream = new FileStream("state.info", 36:         FileMode::Create, FileAccess::Write, FileShare::None); 37: 38:     if( !formatter || !stream ) 39:         return; 40: 41:     formatter->Serialize(stream, m_pStateInfo ); 42:     stream->Close(); 43: 44:     return; 45: } 46: 47: void RestoreState() 48: { 49:     IFormatter* formatter = new BinaryFormatter(); 50:     Stream* stream = new FileStream("state.info", 51:         FileMode::Open, FileAccess::Read, FileShare::Read); 52:     m_pStateInfo=dynamic_cast<StateInfo*>(formatter->Deserialize(stream)); 53:     stream->Close(); 54: 55:     // restore form properties 56:     this->Size = m_pStateInfo->Form_Size; 57:     this->Location = m_pStateInfo->Form_Location; 58:     this->m_tbNonSerializedString->Text=m_pStateInfo->NonSerializedString; 59:     this->m_tbSerializedString->Text = m_pStateInfo->SerializedString; 60: 61:     return; 62: } 

Because the SaveState function is not called anywhere (and therefore serialization will not occur), call the SaveState function within the Save button's event handler named Serialize_Click.

Deserializing is very similar to serializing an object. Create another member function within the ObjectSerializationForm class named RestoreState. Hook this up to the Load button by calling it within the Load_Click event handler for that button. Just as you did within the SaveState function, create a BinaryFormatter object and a FileStream object. The FileStream object, however, will open the file in read rather than write mode. To deserialize an object, call the Deserialize member function contained within the BinaryFormatter object, passing the FileStream object as the only parameter. This function returns a generic Object, so you must cast the return value to your StateInfo member variable. The last step in the deserialization process is to transfer the properties of the StateInfo object into the corresponding properties or member variables in your Windows Form class, as shown on line 56 of Listing 24.3.

The last step to complete your project is to add some additional namespace declarations and to output the values of the two strings contained within the StateInfo object. The code that was added to support serialization requires the use of six additional namespaces contained in two assemblies. Import the appropriate assemblies and declare the namespaces you will use by adding the following code at the top of the ObjectSerialization.cpp file:

 #using <System.Data.dll> #using <System.Xml.dll> using namespace System::Collections; using namespace System::ComponentModel; using namespace System::Data; using namespace System::Runtime::Serialization::Formatters::Binary; using namespace System::IO; using namespace System::Runtime::Serialization; 

Finally, write the values of the two string objects contained within the StateInfo private member variable by setting the Text property of the m_tbObjectDump within the Dump_Click event handler.

You are now ready to compile and launch your application. First, set two values for each of the text boxes by entering a string and clicking the Set button. You can verify the values of the two strings by clicking the Dump button. Next, move and resize your form so that it is in a different state from what it was when initially launched. Save the current state of the form by clicking the Serialize button. In order to ensure that the serialization was successful, once again change the values of the two text boxes and then move and resize your form to a different location. Click the Dump button to make sure the values are in fact different. Now you can deserialize the StateInfo object by clicking the Load button. Once you do that, your form will automatically resize itself and move to the location at the point where you clicked the Serialize button. Finally, click the Dump button. Notice that the serialized string did in fact revert back to its serialized state, but the nonserialized string is now empty because its value was not serialized.


   
Top


Sams Teach Yourself Visual C++. NET in 24 Hours
Sams Teach Yourself Visual C++.NET in 24 Hours
ISBN: 0672323230
EAN: 2147483647
Year: 2002
Pages: 237

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net