Friday, April 13, 2012

Using IsolatedStorage in Silverlight

Isolated Storage is a data storage mechanism that provides facility to store data in a file.

Storage location of IsolatedStorge is based on  application and user identity. each application have separate store.

With isolated storage, data is always isolated by user and by assembly.

System.IO.IsolatedStorage namespace contains types that allow user to create/update and use isolated store.

In Silverlight, there is no concept of Cookies to store information, so IsolatedStorage is great replacement of Cookies in Silverlight application.

In this post, i am going to show you how Create IsolatedStore and save information into it.

First you have to add System.IO.IsolatedStorage namespce.


There are two ways to save Information into IsolatedStorage.

Scenario 1: StoreForSite

 private IsolatedStorageFile isolatedStorage;
 private readonly String applicationDirectory;
 private readonly String settingsFilePath;
 
 this.isolatedStorage = IsolatedStorageFile.GetUserStoreForSite();
 this.applicationDirectory = "UserSettingsDirectory";
 this.settingsFilePath = String.Format("{0}\\settings.xml", this.applicationDirectory);  
 
    public void WriteSettingsData(String content)
    {
       if (this.isolatedStorage == null)
       {
          return false;
       }
       if (!this.isolatedStorage.DirectoryExists(this.applicationDirectory))
       {
           this.isolatedStorage.CreateDirectory(this.applicationDirectory);
       }
       using (IsolatedStorageFileStream fileStream =
         this.isolatedStorage.OpenFile(this.settingsFilePath, 
             System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
       using (StreamWriter streamWriter = new StreamWriter(fileStream))
       {
         streamWriter.Write(content);
       }
    }

In above code, first of all create object of IsolatedStorageFile.
The IsolatedStorageFile class provides functionality to obtain, delete and manage isolated storage.

Then write information into IsolatedStorage using IsolatedStoageFileStream using StreamWriter.
IsolatedStorageFileStream class handles reading and writing files data into store.

Scenario 2: StoreForApplication

   public class LoginInfo
   {
      public string Username { get; set; }
      public string Password { get; set; }
      public bool RememberCredentials { get; set; }
   }
   private void Save_Click(object sender, RoutedEventArgs e)
   {
      
      LoginInfo LoginInformation = new LoginInfo();
      LoginInformation.Username = UserNameTextBox.Text;
      LoginInformation.Password = PasswordTextBox.Text;

      IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
      using (IsolatedStorageFileStream fileStream = 
          appStore.OpenFile("hirenlog.log", FileMode.Create))
      {
          var serializer = new DataContractSerializer(typeof(LoginInfo));
          if (fileStream != null)
          {
             serializer.WriteObject(fileStream, LoginInformation);
          }
      }          
      UserNameTextBox.Text = "";
      PasswordTextBox.Text = "";
      
     }

you can also store whole Data contract/Generic class information into IsolatedStore.

As shown in above code, i have created Object of IsolatedStorageFile from StoreForApplication.
After that create file using IsolatedStorageFileStream and give FileName to save.
Then Serialize you Entity using DataContractSerializer and write information.

Now, how get data from IsolatedStorage.



For scenario 1 

  public String GetSettingsData()
  {
     if (this.isolatedStorage == null)
     {
         return String.Empty;
     }
     if (this.isolatedStorage.FileExists(this.settingsFilePath))
     {
         using (IsolatedStorageFileStream fileStream = 
           this.isolatedStorage.OpenFile(this.settingsFilePath, 
               System.IO.FileMode.Open, System.IO.FileAccess.Read))
         using (StreamReader streamReader = new StreamReader(fileStream))
         {
             return streamReader.ReadToEnd();
         }
     }
     return string.Empty;
  }
 

For scenario 2

  private void GetDataContract_Click(object sender, RoutedEventArgs e)
  {
     LoginInfo result = new LoginInfo();
     IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
     if (appStore.FileExists("hirenlog.log"))
     {
        using (IsolatedStorageFileStream fileStream = 
             appStore.OpenFile("hirenlog.log", FileMode.Open))
        {
            var serializer = new DataContractSerializer(typeof(LoginInfo));
            if (fileStream != null)
            {
                 result = (LoginInfo)serializer.ReadObject(fileStream);
            }
        }
     }
  }

So, this way you can get data from IsolatedStorage using StreamReader for simple text data and Serializer for DataContract.

Click IsolatedStorageInSilverlight To Download Source.

No comments:

Post a Comment