Popular Posts

Monday, July 2, 2012

Store Value at Application level in silverlight

we can use isolation level for storing the value at application level similar to session.

Example:

public static void SaveToIsolatedStorage( string fileName, object objectToSave )
{
    using ( IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication() )
    {
        using ( IsolatedStorageFileStream stream = file.OpenFile( fileName, FileMode.Create ) )
        {
            XmlSerializer serializer = new XmlSerializer( objectToSave.GetType() );
            serializer.Serialize( stream, objectToSave );
        }
    }
}
 
public static T LoadFromIsolatedStorage<T>( string fileName ) where T : class
{
    if ( string.IsNullOrEmpty( fileName ) )
    {
        throw new ArgumentNullException( "fileName", "Cannot be null or empty." );
    }
 
    using ( IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication() )
    {
        if ( file.FileExists( fileName ) )
        {
            using ( IsolatedStorageFileStream stream = file.OpenFile( fileName, FileMode.Open ) )
            {
                XmlSerializer serializer = new XmlSerializer( typeof( T ) );
                return serializer.Deserialize( stream ) as T;
            }
        }
 
        return default( T );
    }
}