ARTICLE

Understanding Isolated Storage in Silverlight

Posted by Vishal Nayan Articles | Silverlight with C# February 05, 2011
In the previous article we learned the fundamentals of Isolated Storage and how to write to files in isolated storage using the same classes you use for ordinary file access in a .NET application, such as StreamWriter and BinaryWriter.
Reader Level:

Background:

In the previous article we learned the fundamentals of Isolated Storage and how to write to files in isolated storage using the same classes you use for ordinary file access in a .NET application, such as StreamWriter and BinaryWriter. To read from them, you use the corresponding StreamReader and BinaryReader classes. Although this approach gives us the most direct control over your files, it's not the only option.

So, here in the second of a two-part series of articles, we will learn about the XmlSerializer class, which provides a higher-level alternative that allows you to serialize and deserialize objects rather than write and read individual pieces of data.

How it works:

XmlSerializer works by converting a live object into a stream of bytes, which you can push out to any stream and perform the reverse trick and convert a stream of bytes into an object instance.

How to use it:

we need to add, System.Xml.Serialization.dll

Advantage with XML Serializer:

XmlSerializer gives you a clean, concise way to store an entire object's worth of information. Ideally, the classes we use to store information with XmlSerializer will be simple data packages with little or no functionality built in.

So let us start programming it to explore more of it.

Step 1: Create a Silverlight application project and name it: XMLSerializerIsolatedStorage

Step 2: In the previous article we were saving the full name of any employee, so we will create a class which will be serialized

public class Employee
    {
        public string Name { get; set; }
        public DateTime? DateOfBirth { get; set; }

        public Employee(string sName,DateTime? dateOfBirth)
        {
            Name = sName;           
            DateOfBirth = dateOfBirth;
        }

        // Required for serialization support.
        public Employee() { }
    }

Step 3: we will add two namespaces with which we are going to work.

using System.IO.IsolatedStorage;
using System.Xml.Serialization;

add assembly reference ;

Isolated1.gif

Step 4: Now let us create a XAML to input employee details.

We will have textbox for name and a calendar. The left hand side we will have a listbox to show the details.

Isolated2.gif

Step 5: Let us write a handler for the add button, listbox selection changed and delete button. Before that we need to create an object of XmlSerializer class of our class type which is Employee

  // requires System.Xml.Serialization.dll refrence
   private XmlSerializer serializer = new XmlSerializer(typeof(Employee));
   private Person currentEmployee;


We will create storage object for application scope, you can create it for Site as well.

Isolated3.gif

Here is the add button handler;

private void cmdAdd_Click(object sender, RoutedEventArgs e)
        {

            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {               
                if (currentEmployee != null)
                {
                    store.DeleteFile( currentEmployee.Name + currentEmployee.DateOfBirth + ".employee");
                }              
                    //Create employee class object
                    Employee emp = new Employee(txtFirstName.Text, dpDateOfBirth.SelectedDate);

                    // We will create  a data file with employee name
                    using(FileStream sw =  store.CreateFile(emp.Name + ".employee"))
                    {
                        //Serializer method is used to serialize the object, which is emp here;
                        serializer.Serialize(sw,emp);                   
                    }
                //Let us add the information in our listbox to show
                lstPeople.ItemsSource = store.GetFileNames("*employee");
                currentEmployee =null;
                txtFirstName.Text= "";            
            }
        }

Isolated4.gif

Step 6: Now let us write handler for ListBox Selection Changed. The idea behind that is that when we hover over a listbox item, we will populate in textBox. When the user clicks one of the employee files in the list, the data is retrieved from isolated storage; we will perform deserialization, back to object from stream.


 
private void lstPeople_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lstPeople.SelectedItem == null)
                return;
            //Define the store object scope,i.e. application or site.
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                //Define the stream object to read , and keep the file mode Open.
                using(FileStream streamReader =store.OpenFile(lstPeople.SelectedItem.ToString(), FileMode.Open))
                {
                    //Cast the object into Class type.
                    //While saving/ serilization , we used Serialize() , similarly now we will use Deserialize()
                    // to get the object back into employee type.

                    currentEmployee = (Employee)serializer.Deserialize(streamReader);

                    //Show the info in textBox.
                    txtFirstName.Text = currentEmployee.Name;
                    dpDateOfBirth.SelectedDate = currentEmployee.DateOfBirth;        
                }    
            }


Step 7 : Let's write handler for Delete button.

private void Delete_Click(object sender, RoutedEventArgs e)
        {
            if (lstPeople.SelectedItem == null) return;

            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                store.DeleteFile(lstPeople.SelectedItem.ToString());
                lstPeople.ItemsSource = store.GetFileNames("*.employee");
                currentEmployee = null;
                txtFirstName.Text = "";               
            }

        }

Step 8: Press F5 and type few employee names, click to save. Select any employee name from list box to view detail in textbox. This all is happening in scope of Isolated Storage as we are using to store the serialized data.

ser-5.JPG

Conclusion :

So we learned how can we use XmlSerializerclass to write to files in isolated storage.

Cheers.

COMMENT USING