Isolated Storage Helper For C# and XAML based Metro Application

This post and helper class is based on work of Jamie Thomson . I thank him lot for that.

Why to use Metro Application Isolated Storage Helper?

This helper class helps you to perform Read,Write and Delete of structured data in Isolated storage folders.

How to use this?

Download Metro Application Isolated Storage Helper from here

You have a class Student



public class Student
    {
        public string Name { get; set; }
        public int RollNumber { get; set; }
    }


You want to save object of Student then you can save it in Local Folder of isolated storage as below


Student objStudent = new Student { Name = "DJ ", RollNumber = 1 };
            var objectStorageHelper = new StorageHelper<Student>(StorageType.Local);            
            objectStorageHelper.SaveASync(objStudent,"abc");



And you can read back Student from isolated storage as below



public async void ReadData()
        {            
            var objectStorageHelper = new StorageHelper<Student>(StorageType.Local);           
            Student objStudent = await objectStorageHelper.LoadASync("abc");
            
        }


Abc is name of the file. If you want to store List<Student> then you can do that as following,



List<Student> lstStudent = new List<Student>()
                                        {new Student { Name = "DJ ", RollNumber = 1 },
                                         new Student { Name = "debugmode", RollNumber = 2 }
                                        };

            var objectStorageHelper = new StorageHelper<List<Student>>(StorageType.Local);
            objectStorageHelper.SaveASync(lstStudent, "abc");



You can read List<Student> from local folder of isolated storage as following



public async void ReadData()
        {            
            var objectStorageHelper = new StorageHelper<List<Student>>(StorageType.Local);           
            List<Student> lstStudent = await objectStorageHelper.LoadASync("abc");
            foreach (var r in lstStudent)
            {
                string n = r.Name;
            }
        }




Background

I was working with storing and retrieving structured data in Isolated Storage. While Binging I came across nicely written Generic Object Storage Helper for WinRT . This is written by Jamie Thomson . When I tried using this utility I came across an exception. I tried to store object of Student as following.


private void btnSaveData_Click_1(object sender, RoutedEventArgs e)
        {
            Student objStudent = new Student { Name = "Hary ", RollNumber = 1 };
            var objectStorageHelper = new ObjectStorageHelper<Student>(StorageType.Local);            
            objectStorageHelper.SaveASync(objStudent);
        }

But while running the program I came across exception as below,

image

After inspecting I found that library is written in Developer Preview and few API has been changed in Consumer Preview. Thankfully Jamie Thomson has put the source code on the CodePlex also. A big thank to him for the same. Rather than adding DLL and working with API, I copied and pasted code in my program and started to debug that.

First changes in API from DP to CP was that there were no TryMoveToRecycleBin in StorageDeleteOption enum

image

Now StorageDeleteOption enum contains only two values as below,

image

So I replaced above line of code as below,

image

The Second changes from DP to CP I found was removal of OpenWrite and OpenRead method from IRandomAcccessStream interface

image

Where readStream is defined as below,

image

And OpenWrite has been replaced with AsStreamForWrite

image

I have modified code to explicitly take filename as well. After these changes have been done Code was ready to be used in Consumer Preview. Updated helper class code is as following,

 



     public enum StorageType
    {
        Roaming, Local, Temporary
    }

    public class ObjectStorageHelper<T>
    {
        private ApplicationData appData = Windows.Storage.ApplicationData.Current;
        private XmlSerializer serializer;
        private StorageType storageType;

        
        public ObjectStorageHelper(StorageType StorageType)
        {
            serializer = new XmlSerializer(typeof(T));
            storageType = StorageType;
        }

        public async void DeleteASync(string FileName)
        {
            FileName = FileName + ".xml";
            try
            {
                StorageFolder folder = GetFolder(storageType);

                var file = await GetFileIfExistsAsync(folder, FileName);
                if (file != null)
                {
                    await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public async void SaveASync(T Obj,string FileName)
        {

            FileName = FileName + ".xml";
            try
            {
                if (Obj != null)
                {
                    StorageFile file = null;
                    StorageFolder folder = GetFolder(storageType);
                    file = await folder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);

                    IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite);
                    Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result;
                    serializer.Serialize(outStream, Obj);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task<T> LoadASync(string FileName)
        {
            FileName = FileName + ".xml";
            try
            {
                StorageFile file = null;
                StorageFolder folder = GetFolder(storageType);
                file = await folder.GetFileAsync(FileName);
                IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);
                Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result;
                return (T)serializer.Deserialize(inStream);
            }
            catch (FileNotFoundException)
            {
                //file not existing is perfectly valid so simply return the default 
                return default(T);
                //throw;
            }
            catch (Exception)
                 {
                //Unable to load contents of file
                throw;
            }
        }

        private StorageFolder GetFolder(StorageType storageType)
        {
            StorageFolder folder;
            switch (storageType)
            {
                case StorageType.Roaming:
                    folder = appData.RoamingFolder;
                    break;
                case StorageType.Local:
                    folder = appData.LocalFolder;
                    break;
                case StorageType.Temporary:
                    folder = appData.TemporaryFolder;
                    break;
                default:
                    throw new Exception(String.Format("Unknown StorageType: {0}", storageType));
            }
            return folder;
        }

        private async Task<StorageFile> GetFileIfExistsAsync(StorageFolder folder, string fileName)
        {
            try
            {
                return await folder.GetFileAsync(fileName);

            }
            catch
            {
                return null;
            }
 }
    }



In this way you can work with structured data in XAML based Metro Application for Windows 8. I hope this post is useful. Thanks for reading.

Protecting password or any data in Windows Phone 7 using Data Protection API

There may be many scenarios, when you need to save data in protected form for your application in isolated storage. Of course you have an option

  • To encrypt the data with some encryption algorithm
  • Save in the isolated storage

Problem with above approach is either you will have to store the key in isolated storage or read it from some external sources. In major scenarios key is residing on the phone itself and it brings the flaw.

Windows Phone Data Protection API helps us to protect data at the application level. On Windows Phone 7 every application has their own key. This key gets created when you first run the application.

Using DP API, all it takes one line of code to encrypt and decrypt the data.

To Encrypt

image

First line of code is converting string to byte array. To encrypt data only you need to pass byte array.

To Decrypt

image

Password is name of the file in which encrypted data is stored. All it takes only one line of code to decrypt.

If you closely look into ProtectedData class,

image

This is static class with two static methods. If required you can pass entropy as parameter also.

Design page

Now let us design a page like below, Design is very simple with one text box taking input to protect the data. There are two buttons, one to protect data and another to decrypt and retrieve protected data.

clip_image001

XAML of design is as below,


<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="PageTitle" Text="protected data" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle2Style}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="80" />
<RowDefinition Height="180" />
</Grid.RowDefinitions>
<TextBox x:Name="txtDataToProtect" HorizontalAlignment="Left" Width="450" Height="80" />
<StackPanel Orientation="Horizontal" Margin="0,0,0,0" Grid.Row="1">
<Button x:Name="btnReteriveData" Content="Reterive" Height="100"  Click="btnReteriveData_Click" Width="200" />
<Button x:Name="btnProtectData" Content="Protect" Height="100"  Click="btnProtectData_Click" Width="260" />
</StackPanel>
</Grid>
</Grid>

Protecting Data


private void btnProtectData_Click(object sender, RoutedEventArgs e)
{
byte[] passwordData = Encoding.UTF8.GetBytes(txtDataToProtect.Text);
byte[] EncryptedPasswordData = ProtectedData.Protect(passwordData, null);
SaveToFile(EncryptedPasswordData, "password");
}

In above code,

  1. We are converting text to byte array
  2. Passing byte array to protect
  3. We are applying no entropy.
  4. Saving protected data to a file called password. We will have to fetch encrypted data from file password while retrieving.
  5. To save protected data calling a function called SaveToFile

SaveToFile function


private void SaveToFile(byte[] EncryptedPasswordData,string FileName)
{
IsolatedStorageFile getApplicationFile = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fileAsStream = new IsolatedStorageFileStream(FileName, System.IO.FileMode.Create, FileAccess.Write, getApplicationFile);
Stream writer = new StreamWriter(fileAsStream).BaseStream;
writer.Write(EncryptedPasswordData, 0, EncryptedPasswordData.Length);
writer.Close();
fileAsStream.Close();
}

In above code,

  1. We are passing byte array to save
  2. We are passing filename to say where to save the data in application
  3. Reading application file and opening it as file stream
  4. Writing byte array to file stream.

Decrypting data


private void btnReteriveData_Click(object sender, RoutedEventArgs e)
{
byte[] data = ReadFromFIle("password");
byte[] passwordByte = ProtectedData.Unprotect(data, null);
string password = Encoding.UTF8.GetString(passwordByte, 0, passwordByte.Length);
txtDataToProtect.Text = password;

}

In above code,

  1. We are first reading encrypted data from the isolated storage file. If you notice file name is same.
  2. Calling unprotect method and passing encrypted byte array to decrypt.
  3. Converting decrypted byte array to string and displaying in text box

ReadFromFile function


private byte[] ReadFromFIle(string FileName)
{

IsolatedStorageFile getApplicationFile = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fileAsStream = new IsolatedStorageFileStream(FileName, System.IO.FileMode.Open, FileAccess.Read, getApplicationFile);
Stream reader = new StreamReader(fileAsStream).BaseStream;
byte[] password = new byte[reader.Length];
reader.Read(password, 0, password.Length);
reader.Close();
fileAsStream.Close();
return password;
}

In above code,

  1. Reading application file and opening it as file stream
  2. Reading byte array to file stream.

If you would have noticed we have not provided KEY either to ENCRYPT or DECRYPT the data.

In this way you can protect data in Windows Phone 7. I hope this post was useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

File Handling in Isolated Storage in Silver Light

Objective

This article will explain,

  1. How to create a text file in IsolatedStorageFile of a SilverLight 2 application.
  2. How to write into a text file in IsoltaedStorageFile.
  3. How to read a text file from IsolatedStorageFile.
  4. How to delete a file from IsolatedStorageFile.

Step 1

Create a SilverLight application. By selecting File->New->Project->SilverLight-> SilverLight Application.Design the XAML page. I am creating three buttons for the purpose of Read, Write and Delete File. There are two text boxes. One to get filename input and other for displaying content from the file and saving content from that text box.

MainPage.Xaml

<UserControl
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243; ns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243; x:Class=”FileReadingandWritingwithIsolatedStorage.MainPage”
Width=”Auto” Height=”Auto” mc:Ignorable=”d”><Grid x:Name=”LayoutRoot” Height=”400″ Width=”600″>

   <Grid.Background>

 <LinearGradientBrush EndPoint=”0.5,1″ StartPoint=”0.5,0″>
 <GradientStop Color=”#FF000000″/>
<GradientStop Color=”#FFE9DDDD” Offset=”1″/>
</LinearGradientBrush>
</Grid.Background><Grid.RowDefinitions>
<RowDefinition Height=”0.175*”/> <RowDefinition Height=”0.182*”/>  <RowDefinition Height=”0.642*”/>
 </Grid.RowDefinitions>
<TextBox x:Name=”txtFileLabel” HorizontalAlignment=”Left” Margin=”17,18,0,17″ Width=”188″ FontSize=”18″ FontWeight=”Normal” Text=”File Name” TextWrapping=”Wrap” Opacity=”0.3″ Background=”#FF808080″/>
 <TextBox x:Name=”txtFileName” Margin=”252,18,48,17″ Width=”300″ FontSize=”18″ FontWeight=”Bold” Text=”” TextWrapping=”Wrap”/>
<Button x:Name=”btnRead” HorizontalAlignment=”Left” Margin=”17,23,0,8″ Width=”180″ FontSize=”18″ FontWeight=”Bold” Grid.Row=”1″ Content=”Read” Click=”btnRead_Click”/>
<Button x:Name=”btnWrite” Margin=”0,23,36,8″ Width=”180″ FontSize=”18″ FontWeight=”Bold” Grid.Row=”1″ Content=”Write” Click=”btnWrite_Click” d:LayoutOverrides=”Width” HorizontalAlignment=”Right”/>
 <TextBox x:Name=”txtContent” Margin=”30,22,45,34″ Grid.Row=”2″ Text=”” TextWrapping=”Wrap” FontSize=”9″/>
<Button x:Name=”btnDelete” Margin=”235,23,251,8″ Grid.Row=”1″ Content=”Delete File” FontWeight=”Bold” FontSize=”18″ Click=”btnDelete_Click”/>
</Grid>
</UserControl>

 Step 2
Now, writing the code behind to handle the Read and Write Operation. I am using IsolatedStorageFIle class to perform file handling operations.
IsolatedStorageFile

  1. This class is inside the namespace System.IO.IsolatedStorage
  2. We could set domain of IsolatedStorageFile either for SilverLight website or for SilverLight Application.
  3. There are many methods exist inside this to work with File operations. For example, create directory, create file, delete directory, delete file etc. 

How to write into the file?

private void btnWrite_Click(object sender, System.Windows.RoutedEventArgs e){using (var store = IsolatedStorageFile.GetUserStoreForApplication(){
if (!(store.FileExists(txtFileName.Text))){
MessageBox.Show(“File does not exist , we are creating one for you “);
IsolatedStorageFileStream file = store.CreateFile(txtFileName.Text);
file.Close();}
using (StreamWriter sw = new StreamWriter(store.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.Write)))
{
sw.WriteLine(txtContent.Text);
}
txtContent.Text = “”;

txtFileName.Text = “”;
MessageBox.Show(“File Writen”);}}

 Explanation

  1. StreamWriter is being used to write into the file.
  2. StreamWriter is inside the namespace System.IO.
  3. We are opening the ISolatedStorageFile for the SilverLight Application.
  4. We are checking, that if file name provided by user does not exist then create a new one with the provided name.
  5. We are opening the file in Write Mode and writing the stream into that.

     How to Read from the file?

private void btnRead_Click(object sender, System.Windows.RoutedEventArgs e){using (var store = IsolatedStorageFile.GetUserStoreForApplication(){
if (!(store.FileExists(txtFileName.Text))){
MessageBox.Show(“File does not exist “);
txtFileName.Text = “”;
}
else{
using (StreamReader sr = new StreamReader(store.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.ReadWrite))) {
txtContent.Text = sr.ReadToEnd();
}}}}

Explanation

  1. StreamReader is being used to read from the file.
  2. StreamREader is inside the namespace System.IO.
  3. We are opening the ISolatedStorageFile for the SilverLight Application.
  4. We are checking, that if file name provided by user does not exist then displaying the message that file name does not exist.
  5. We are opening the file in Read Mode and reading the stream into a string.

 How to delete file?

private void btnDelete_Click(object sender, System.Windows.RoutedEventArgs e){
using (var store = IsolatedStorageFile.GetUserStoreForApplication()){
if (!(store.FileExists(txtFileName.Text))){
MessageBox.Show(“File does not exist “);
}
else{ store.DeleteFile(txtFileName.Text);
MessageBox.Show(“Deleted”);}
txtFileName.Text = “”;}}

 Explanation

  1. We are calling the DeleteFile method on instance of ISolatedStorageFile.

Complete code is as below

MainPage.xaml.cs

 

using System;using System.Collections.Generic;

using System.Linq;

using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.IO.IsolatedStorage;
namespace FileReadingandWritingwithIsolatedStorage
{
public partial class MainPage : UserControl{
public MainPage(){

InitializeComponent();
}
private void btnRead_Click(object sender, System.Windows.RoutedEventArgs e)
{
 

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text))){
MessageBox.Show(“File does not exist “);
txtFileName.Text = “”;
}
else
{
using (StreamReader sr = new StreamReader(store.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.ReadWrite)))
{
txtContent.Text = sr.ReadToEnd();
}}}}

private void btnWrite_Click(object sender, System.Windows.RoutedEventArgs e)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text))){
MessageBox.Show(“File does not exist , we are creating one for you “);
IsolatedStorageFileStream file = store.CreateFile(txtFileName.Text);
file.Close();
}
using (StreamWriter sw = new StreamWriter(store.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.Write)))
{
sw.WriteLine(txtContent.Text);
}
txtContent.Text = “”;

txtFileName.Text = “”;
MessageBox.Show(“File Writen”);
}}
private void btnDelete_Click(object sender, System.Windows.RoutedEventArgs e)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text))){
MessageBox.Show(“File does not exist “);
}
else
{
store.DeleteFile(txtFileName.Text);
MessageBox.Show(“Deleted”);
}
txtFileName.Text = “”;
}}}}

Isolated Storage in Silver Light

Why Isolated Storage?

SilverLight applications are partially trusted application, which are running on a sandbox environment. So, SilverLight applications are not allowed to access the file system of the client, where it is running for the security reason. Because it is not safe to allow any SilverLight application to access client computer, this may harm many important system files. Because we know some SilverLight application might be potential malicious application. And we don’t want while browsing, any harmful SilverLight application to access our file system and harm them.But some time, SilverLight application needs some restricted access to client local file system for business requirement. Like Reading and Writing user specific file at client location or saving the personal information specific to user at client side etc. So, above purpose is achieved by SilverLight application using ISOLATED STORAGE.


Cookies and Isolated Storage 

Isolation

Isolated storage is composed of many different unique stores. Each of which can be thought of as its own virtual file system. This virtual file system is in isolation with the file system of operating system, such that malicious SilverLight application can not have access to the original file system.

Location of the Isolated Storage

Operating System

Location

Windows VISTA <SYSDRIVE>\Users\<user>\AppData\LocalLow\Microsoft\Silverlight\is
   
Windows XP <SYSDRIVE>\Document and Settings\<user>\Local Setting\Application data\Microsoft\Silver light\is
   

 SiliverLight application has access to two different stores.


SILVERLIGHT application has access of

  1. User + Application store
  2. User + Site store

Few Important points

  1. A SilverLight Application can access only its own application store. It cannot access store of other application.
  2. The Application Store is based on the, identity of the user and identity of the application.
  3. The identity of the application is full URL of the XAP file of the Silver light Application. For example www.c-sharpcorner.com\Application1.xap
  4. Application identity is case insensitive.


 Sample:
This sample will demonstrate how to use with Application level setting of IsolatedStorageSetting class.

  1. After entering User Name is textbox , when user will click Save Me. That user name will get added in the isolated file created for the application.
  2. On clicking on Reset Me button value saved against UserName key, will get deleted from the isolated file.
  3. At each time application will loaded, saved UserName will get display in the textbox

Step 1

Create a private global variable of the type IsolatedStorageSetting for the Application level.
private IsolatedStorageSettings app = IsolatedStorageSettings.ApplicationSettings;

Step 2

On the Save button click, we will be checking if checkbox is checked, we will check whether

  1. UserName key is existing in App or not. If not, we will add UserName key.
  2. We will set value for UserName key from the user name text box.
  3. App.add() is used to add new key in the application.
private void btnSave_Click(object sender, System.Windows.RoutedEventArgs e){

if (chkSave.IsChecked == true)
{
if (!(app.Contains(“UserName”)))
{
app.Add(“UserName”,“User Name has not Set “);
}
app[“UserName”] = txtUname.Text;
} }

 Step 3
On the Reset button, we are simple removing the key from the app setting.

private void btnReset_Click(object sender, System.Windows.RoutedEventArgs e)

{

app.Remove(“UserName”);

txtUname.Text = “”;}

 Step 4
On the Page Load, I am displaying the saved value for the key UserName from the isolated storage.

void MainPage_Loaded(object sender, RoutedEventArgs e){

if (app.Contains(“UserName”))
{
txtUname.Text = app[“UserName”].ToString();
}}

 So, the complete code is as below,
MainPage.Xaml

<UserControl x:Class=”IsolatedStorageSample1.MainPage”
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

Width=”Auto” Height=”Auto”>

<Grid x:Name=”LayoutRoot” Background=”#FF7F4343″ Width=”400″ Height=”400″>

<Grid.ColumnDefinitions>    
 <ColumnDefinition Width=”0.385*”/>
<ColumnDefinition Width=”0.615*”/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>

<RowDefinition Height=”0.25*”/>
<RowDefinition Height=”0.157*”/>
<RowDefinition Height=”0.593*”/>
 </Grid.RowDefinitions>
<TextBox x:Name=”txtUname” Margin=”10,10,10,10″ Grid.Column=”1″ Text=”” TextWrapping=”Wrap”Background=”#FF230303″ BorderThickness=”2,2,2,2″ FontSize=”16″ FontWeight=”Bold” Foreground=”#FFF81616″/>
 <TextBlock Margin=”8,8,8,8″ Text=”UserName” TextWrapping=”Wrap” FontSize=”12″ FontWeight=”Bold”Foreground=”#FF342A2A” FontFamily=”Arial Rounded MT Bold”/>
<CheckBox x:Name=”chkSave” Margin=”10,10,10,10″ Grid.Row=”1″ Content=”Save User Name” IsChecked=”True” FontWeight=”Bold” FontSize=”12″
BorderThickness=”2,2,2,2″ Foreground=”#FF150808″ FontFamily=”Arial Rounded MT Bold”/>
<Grid Margin=”8,10,12,8″ Grid.Column=”1″ Grid.Row=”1″>

 <Grid.ColumnDefinitions>

<ColumnDefinition Width=”0.385*”/>
<ColumnDefinition Width=”0.615*”/>
 </Grid.ColumnDefinitions>

<Button x:Name=”btnSave” Margin=”2,2,2,2″ Content=”Save Me” Grid.Row=”0″ Grid.Column=”0″ Click=”btnSave_Click”/>

<Button x:Name=”btnReset” Margin=”2,2,2,2″ Content=”Reset Me “ Grid.Row=”0″ Grid.Column=”1″ Click=”btnReset_Click”/>
 </Grid>
</Grid>
</UserControl>

 MainPage.Xaml.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.IO.IsolatedStorage;

 namespace IsolatedStorageSample1{
public partial class MainPage : UserControl{
private IsolatedStorageSettings app = IsolatedStorageSettings.ApplicationSettings;
public MainPage(){

InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e){
if (app.Contains(“UserName”)){
txtUname.Text = app[“UserName”].ToString();
}}
private void btnSave_Click(object sender, System.Windows.RoutedEventArgs e)

{
if (chkSave.IsChecked == true){
if (!(app.Contains(“UserName”)))
{
app.Add(“UserName”,“User Name has not Set “);
}
app[“UserName”] = txtUname.Text;}}
private void btnReset_Click(object sender, System.Windows.RoutedEventArgs e){
app.Remove(“UserName”);

txtUname.Text = “”;}}}

 Output:


After clicking Refresh again we will get the same output. If we click Reset and then press F5, we will get output as below.


Quota in Isolated Storage

  1. A quota is limit on the amount of isolated storage space that can be used by the application.
  2. A Quota Group is group of isolated Store that shares the same quota.
  3. In Silver Light, stores are grouped by the site. So all the application with same site identity shares the same quota.
  4. Isolated Storage could have zero or more quota groups.

  1. An Application can request more space for the quota group

      

  2.    Sample on how to modify the quota?
    I have added the below code on the click event of Save Button. So now the save Button click event is as below. I have modified the above code sample. See the code in Red rectangle.
private void btnSave_Click(object sender, System.Windows.RoutedEventArgs e){

if (chkSave.IsChecked == true){
if (!(app.Contains(“UserName”)))
{
app.Add(“UserName”,“User Name has not Set “);
}
app[“UserName”] = txtUname.Text;
}
using (var store = IsolatedStorageFile.GetUserStoreForApplication()){
int spaceneed = 1024 * 1024 * 5;
if (store.AvailableFreeSpace < spaceneed){
if (store.IncreaseQuotaTo(store.Quota + spaceneed)){
MessageBox.Show(“User Has approved the quota Increase”);
MessageBox.Show(store.AvailableFreeSpace.ToString());
}
else{
MessageBox.Show(“User Has Not Approved the quota Increase “);
MessageBox.Show(store.AvailableFreeSpace.ToString());
}} } }

 Output
User is getting prompt for Approval.


 When User is not approving means selecting “No”. The default size is getting displayed in message box.


When User is approving means selecting “Yes”. The increased size is getting displayed in message box.