Example Serializing and deserializing XML data in isolated storage
The code in Listings 15.3 and 15.4 shows an example Silverlight application that accepts data from TextBox and RadioButton controls and writes that data to an object. The example code serializes the object into XML format and stores it in the isolated local file system. Then the code reads the XML file from the isolated local file system and deserializes the XML data back into an object.
The code in Listing 15.3 implements a simple form with two TextBox controls — NameText and EmailText. The code also implements two Button controls — SerializeBtn and DeserializeBtn — that are used to initiate an XmlSerializer to serialize and deserialize an object. A TextBlock control — myText — is nested inside a ScrollViewer control to display the results of the serialized and deserialized object.
LISTING 15.3
XAML Code That Implements Form and Button Controls to Collect Data That Will Be Used to Create an Object That Will Be Serialized and Then Deserialized
<UserControl x:Class="SerializationApp.Page"
xmlns="http://schemas.microsoft.com/client/2 0 07" xmlns:x="http://schemas.microsoft.com/winfx/2 00 6/xaml" Width="60 0" Height="3 00">
<Grid x:Name="LayoutRoot" Background="LightBlue"> <TextBox x:Name = "NameText" Text="Full Name" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="20,20" Width="200" Height="3 0"/> <TextBox x:Name = "EmailText" Text="Email Address" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="20,70" Width="200" Height="3 0"/> <Button x:Name="SerializeBtn" Content="Serialize"
VerticalAlignment="Top" HorizontalAlignment="Left" Margin="20,13 0" Height="3 0" Width="100 <Button x:Name="DeSerializeBtn VerticalAlignment="Top Margin="14 0,13 0" Height="3 0" Width="100 <ScrollViewer Background="White"
HorizontalScrollBarVisibility="Auto" HorizontalAlignment="Right" Margin="10" Width="300" Height="250"> <TextBlock x:Name="myText"/> </ScrollViewer> </Grid> </UserControl>
Content="Deserialize"
HorizontalAlignment="Left"
The code in Listing 15.4 adds a reference to the System.Xml.Serialization library that includes the Silverlight XmlSerializer class. It also adds references to the System.IO and System.IO.IsolatedStorage libraries to provide access to the StringReader and IsolatedStorageFile classes.
The code defines an IsolatedStorageFile named localStore as well as an IsolatedStorageFileStream named localStream that is used to store and retrieve an XML file.
At the bottom of the code in Listing 15.4, a ContactData class is defined with the XmlRoot decorator. The ContactData class contains two string members — FullName and EmailAddr — which are defined with the XmlElement decorator.
Inside the Page() constructor, the code initializes the localStore object to the current application's isolated local file system. Then the code attaches the doSerialize() and doDeserialize() Click event handlers to the SerializeBtn and DeserializeBtn controls, respectively.
Inside the doSerialize() event handler, the code first initializes the localStream object by creating a file named contact.xml in the isolated file system using the FileMode.Create argument. Then the code creates an instance of the ContactData class named contact from the values of NameText.Text and EmailText.Text.
Then the code creates an XmlSerializer object — serialize — using the GetType() function of the contact object using the following line of code:
XmlSerializer serializer = new XmlSerializer(contact.GetType());
Then the Serialize() function of the serialize object is used to write the contact data object to the contact.xml file using the localStream object, as shown in the following line of code:
serializer.Serialize(localStream, contact);
The code then closes the localStream and reopens it in Open mode. The contents of the file are written to the Text property of the myText TextBlock to be displayed.
Inside the doDeserialize() event handler, the code first initializes the localStream object by opening a file named contact.xml in the isolated file system using the FileMode.Open argument. Then the code creates a blank instance of the ContactData class named contact.
Then the code creates an XmlSerializer object — serialize — using the GetType() function of the contact object using the following line of code:
XmlSerializer serializer = new XmlSerializer(contact.GetType());
The Deserialize() function of the serialize object is then used to read the contact.xml file using the localStream object and sets the value of the contact data object as shown in the following code:
contact = serializer.Deserialize(localStream);
The code closes the localStream and writes a formatted version of the contact object to the Text property of the myText TextBlock to be displayed.
The results of the code in Listings 15.3 and 15.4 are shown in Figure 15.2. The user types a name and e-mail address in the text boxes. When the Serialize button is clicked, the data that is input by the user is written to an object that is serialized into XML, stored in the local file system, and displayed in the scroll viewer. When the user clicks Deserialize, the XML file is read from the local file system and deserialized into an object that is displayed in the scroll viewer.
LISTING 15.4
C# Code That Implements an XmlReader and XmlWriter to Read and Write XML Data using System;
using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input;
using System.Xml.Serialization; using System.IO.IsolatedStorage; using System.IO;
namespace SerializationApp {
public partial class Page : UserControl {
IsolatedStorageFile localStore; IsolatedStorageFileStream localStream;
InitializeComponent();
localStore = IsolatedStorageFile.GetUserStoreForApplication();
SerializeBtn.Click += new RoutedEventHandler(doSerialize); DeSerializeBtn.Click += new RoutedEventHandler(doDeSerialize
void doSerialize(object sender, RoutedEventArgs e) {
localStream = new IsolatedStorageFileStream("contact.xml", continued
LISTING 15.4
(continued)
FileMode.Create, localStore);
ContactData contact = new ContactData(); contact.Name = NameText.Text; contact.Email = EmailText.Text;
XmlSerializer serializer = new XmlSerializer(contact.GetType()) serializer.Serialize(localStream, contact); localStream.Close();
localStream = new IsolatedStorageFileStream("contact.xml",
FileMode.Open, localStore);
StreamReader sReader = new StreamReader(localStream);
myText.Text = sReader.ReadToEnd();
sReader.Close();
localStream.Close();
void doDeSerialize(object sender, RoutedEventArgs e) {
localStream = new IsolatedStorageFileStream("contact.dat",
FileMode.Open, localStore);
ContactData contact = new ContactData();
XmlSerializer serializer = new XmlSerializer(contact.GetType()); contact = serializer.Deserialize(localStream) as ContactData; localStream.Close();
myText.Text = String.Format("Full Name: {0}\r\nEmail: {1}", contact.Name, contact.Email);
[XmlRoot("ContactsXml")]
public class ContactData {
public ContactData() {
private string FullName = ""; [XmlElement("FullNameM)]
public string Name {
get { return this.FullName; } set { this.FullName = value; }
private string EmailAddr = ""; [XmlElement("Email")]
public string Email {
get { return this.EmailAddr; } set { this.EmailAddr = value; }
FIGURE 15.2
Silverlight application that serializes data from TextBox and RadioButton controls, writes the XML in a TextBlock, and then deserializes the XML
FIGURE 15.2

Average user rating: 3 stars out of 2 votes
Responses
-
Dan10 months ago
- Reply