Click here to Skip to main content
15,867,686 members
Articles / Mobile Apps / Windows Phone 7

Simple Data Serialization on WP7

Rate me:
Please Sign up or sign in to vote.
4.94/5 (8 votes)
10 Feb 2011CPOL2 min read 35.8K   7   6
You've got a class that contains data that you want to be able to save and load in IsolatedStorage on Windows Phone 7.

You've got a class that contains data that you want to be able to save and load in IsolatedStorage on Windows Phone 7. How would you go about doing that? There is more than one way, but I wanted to share a generic solution for didactic purposes; I'm finding that many beginners like to start off with a single satisfying solution and branch off into specialized solutions later. Let's say that you are starting off with a stereotypical Employee class.

C#
class Employee 
{ 
     public int EmployeeNumber { get; set; } 
     public string Name { get; set; } 
     public string Department { get; set; } 
}

There are a couple of problems with this employee class that makes it unsuitable for the type of serialization that will be used. First, the class isn't marked as public. This is a requirement for the DataContract serializer. Secondly, the class needs to be marked as serializable and the properties to be serialized must be marked. We mark the class as serializable by giving it the [DataContract] attribute. Each property that needs to be serialized must be marked with the [DataMember] attribute. When we apply these changes, the class looks like the following:

C#
[DataContract] 
public class Employee  
{  
     [DataMember] 
     public int EmployeeNumber { get; set; }  
     [DataMember] 
     public string Name { get; set; }  
     [DataMember] 
     public string Department { get; set; }  
}

There's another requirement that the class already met that I didn't mention. The class needs to have a default constructor. Since we've not given this class a default constructor, the runtime will provide one. Now that we have a serializable class, we need a way to serialize it. The DataContractSerializer would be used to handle both serialization and deserialization of the class. In its simplest form, you only need to provide the type that the serializer will handle. So a serializer could be created with the following code:

C#
DataContractSerializer mySerializer = new DataContractSerializer(typeof(Employee)); 

That serializer can be used to read or write your object to a stream such as a file stream, network stream, or memory stream. I've set forth to only save and read contents from a file stream. So I've made a generic class that contains most of the logic to do that.

C#
using System; 
using System.IO; 
using System.IO.IsolatedStorage; 
using System.Runtime.Serialization; 
 
 
public class DataSaver<MyDataType> 
{ 
    private const string TargetFolderName = "MyFolderName"; 
    private DataContractSerializer _mySerializer; 
    private IsolatedStorageFile _isoFile; 
    IsolatedStorageFile IsoFile 
    { 
        get 
        { 
            if (_isoFile == null) 
                _isoFile = System.IO.IsolatedStorage.
                            IsolatedStorageFile.GetUserStoreForApplication(); 
            return _isoFile; 
        } 
    } 
 
    public DataSaver() 
    { 
        _mySerializer = new DataContractSerializer(typeof(MyDataType)); 
    } 
 
    public void SaveMyData(MyDataType sourceData, String targetFileName) 
    { 
        string TargetFileName = String.Format("{0}/{1}.dat", 
                                       TargetFolderName, targetFileName); 
        if (!IsoFile.DirectoryExists(TargetFolderName)) 
            IsoFile.CreateDirectory(TargetFolderName); 
        try 
        { 
            using (var targetFile = IsoFile.CreateFile(TargetFileName)) 
            { 
                _mySerializer.WriteObject(targetFile, sourceData); 
            } 
        } 
        catch (Exception e) 
        { 
            IsoFile.DeleteFile(TargetFileName); 
        } 
 
 
    } 
 
    public MyDataType LoadMyData(string sourceName) 
    { 
        MyDataType retVal = default(MyDataType); 
        string TargetFileName = String.Format("{0}/{1}.dat", 
                                              TargetFolderName, sourceName); 
        if (IsoFile.FileExists(TargetFileName)) 
            using (var sourceStream = 
                    IsoFile.OpenFile(TargetFileName, FileMode.Open)) 
            { 
                retVal = (MyDataType)_mySerializer.ReadObject(sourceStream); 
            } 
        return retVal; 
    } 
}

I've hard coded the folder name in which the data will be saved (feel free to save that). When using the class, you only need to pass it the object to be saved and the name of the file that it will use.

C#
//declare instance 
DataSaver<Employee> myEmployeeDataSaver = 
              new DataSaver<Employee>(); 
 
//read Usage 
var EmployeeData = myEmployeeDataSaver.LoadMyData(
                          "MyEmployeeDataFileName"); 
 
//save Usage 
myEmployeeDataSaver.SaveMyData(myEmployee,"MyEmployeeDataFileName"); 

That should be enough to get you started. I'm working on a much more complete explanation to be shared later.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
I attended Southern Polytechnic State University and earned a Bachelors of Science in Computer Science and later returned to earn a Masters of Science in Software Engineering. I've largely developed solutions that are based on a mix of Microsoft technologies with open source technologies mixed in. I've got an interest in astronomy and you'll see that interest overflow into some of my code project articles from time to time.



Twitter:@j2inet

Instagram: j2inet


Comments and Discussions

 
Questionusing var EmployeeData to extract objects Pin
Khayam Gondal24-Jun-13 3:41
Khayam Gondal24-Jun-13 3:41 
GeneralMy vote of 5 Pin
Lindrandir2-Nov-11 6:44
Lindrandir2-Nov-11 6:44 
QuestionHmm why? Pin
RredCat18-Feb-11 23:04
professionalRredCat18-Feb-11 23:04 
AnswerDataContractSerializer vs XmlSerializer Pin
Joel Ivory Johnson20-Feb-11 2:39
professionalJoel Ivory Johnson20-Feb-11 2:39 
AnswerVery usefull article Pin
asWorks2387918-Feb-11 21:14
asWorks2387918-Feb-11 21:14 
GeneralMy vote of 5 Pin
defwebserver18-Feb-11 2:04
defwebserver18-Feb-11 2:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.