×
Namespaces

Variants
Actions
(Difference between revisions)

Introduction and best practices for IsolatedStorageSettings

From Nokia Developer Wiki
Jump to: navigation, search
jinek (Talk | contribs)
(Jinek -)
jinek (Talk | contribs)
(Jinek -)
Line 1: Line 1:
 
[[Category:Draft]]
 
[[Category:Draft]]
{{Abstract|This article shows most convenient way of using IsolatedStorageSettings.}}
+
{{Abstract|This article explains how to work with IsolatedStorageSettings.}}
 
{{ArticleMetaData <!--v1.2-->
 
{{ArticleMetaData <!--v1.2-->
 
|sourcecode= [[File:IsolatedStorageSample.zip]]
 
|sourcecode= [[File:IsolatedStorageSample.zip]]
Line 11: Line 11:
  
 
== Introduction ==
 
== Introduction ==
[http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings(v=vs.95).aspx IsolatedStorageSettings] - is dictionary-like way for permanent storing values in  [http://msdn.microsoft.com/en-us/library/x7dzh4ws(v=vs.95).aspx Isolated Storage]. All you have to do to store a value is provide a key for this value and a value itself.
+
[http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings(v=vs.95).aspx IsolatedStorageSettings] - is dictionary-like way for permanent storing values in  [http://msdn.microsoft.com/en-us/library/x7dzh4ws(v=vs.95).aspx Isolated Storage]. All that you have to do to store a value - is provide a key for this value and a value itself.
You can store there anything you want: user settings, layout information or application state. All settings from IsolatedStorageSettings are accessible after application rerun.
+
You can store anything you want: user settings, layout information or application state. All settings from IsolatedStorageSettings are accessible after application shutdown and run again.
In this tutorial we are going create a simple application that keeps one value and then we will extend it for more convenient use.
+
In this tutorial we are going to create a simple application that keeps one boolean value and then we will extend it for more convenient use.
 
== Basic Sample ==
 
== Basic Sample ==
 
# Run Visual Studio 2012
 
# Run Visual Studio 2012
 
# Create new Windows Phone project (7.5 or 8.0)
 
# Create new Windows Phone project (7.5 or 8.0)
#Navigate to MainPage.xaml and replace all control content with one checkbox:
+
#Navigate to MainPage.xaml and replace all control content with one checkbox:<code xml><phone:PhoneApplicationPage x:Class="IsolatedStorageSample.MainPage"
<code xml><phone:PhoneApplicationPage x:Class="IsolatedStorageSample.MainPage"
+
 
                             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 
                             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 
                             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 
                             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Line 31: Line 30:
 
               VerticalAlignment="Top" />
 
               VerticalAlignment="Top" />
 
</phone:PhoneApplicationPage></code>
 
</phone:PhoneApplicationPage></code>
#Navigate to MainPage.xaml.cs and add some code here:
+
#Navigate to MainPage.xaml.cs and add code that does the actual work:<code csharp>using System.IO.IsolatedStorage;
<code csharp>using System.IO.IsolatedStorage;
+
 
using System.Windows;
 
using System.Windows;
  
Line 86: Line 84:
 
}</code>
 
}</code>
 
#Run the application
 
#Run the application
 +
You might see the checkbox which after launch can remember his last state before application shutdown.
 
<gallery>
 
<gallery>
 
File:IsolatedStorageIntro.SimpleApplication.png|Simple setting
 
File:IsolatedStorageIntro.SimpleApplication.png|Simple setting
 
</gallery>
 
</gallery>
IsolatedStorageSettings is easy to use. But if you are going to have more then just one setting-value - syncing, keeping key name, checking if setting exists and saving each time it been updated may become a headache. Better way is to provide all this functionality by helper class only once.
+
IsolatedStorageSettings is easy to use. But if you are going to have more then just one setting-value - syncing, keeping key name, checking if setting exists and saving each time it been updated may become a headache. Better way is to implement all this functionality in helper class only once.
 
== Improvement ==
 
== Improvement ==
Easier way to work with IsolatedStorageSettings is to create a wrapper class around it. It would save the settings every time we update a value (in a thread safe way), it would automatically set default value if setting does not exist (and does not throw an exception when you try to access not existen value), and finally it keeps the key name - we have to provide it only once during property declaration.
+
Easier way to work with IsolatedStorageSettings is to create a wrapper class around it. It would save the setting every time we update it (in a thread safe maner), it would automatically set default value if setting does not exist and finally it would keep the key name - we have to provide it only once during property declaration.
 
Create two new classes:
 
Create two new classes:
 
<code csharp>using System.IO.IsolatedStorage;
 
<code csharp>using System.IO.IsolatedStorage;
Line 176: Line 175:
 
     }
 
     }
 
}</code>
 
}</code>
This class is not hard to understand and you can extend it as you want (may be you want to save values only on application shutdown?).
+
You can extend this classes as you want (may be you want to save values only when application is shutting down?) or you can just copy this classes to your project and start working right now.
Using this class is easier as IsolatedStorageSettings:
+
Using this class is easier then IsolatedStorageSettings:
 
<code csharp>namespace IsolatedStorageSample
 
<code csharp>namespace IsolatedStorageSample
 
{
 
{
Line 184: Line 183:
 
     public partial class MainPage
 
     public partial class MainPage
 
     {
 
     {
 +
        //Setting declaration
 
         static readonly IsolatedStorageProperty<bool> SwitchProperty = new IsolatedStorageProperty<bool>("switch",true);
 
         static readonly IsolatedStorageProperty<bool> SwitchProperty = new IsolatedStorageProperty<bool>("switch",true);
 
          
 
          
Line 202: Line 202:
 
     }
 
     }
 
}</code>
 
}</code>
We are still working only around one setting but as you can see a lot of lines are gone!
+
See? We still have only one setting but a lot of lines are gone! - With ten or more property-settings this class become indispensable.
 
Lets create another setting - FirstRunTimeProperty:
 
Lets create another setting - FirstRunTimeProperty:
 
<code csharp>using System;
 
<code csharp>using System;
Line 245: Line 245:
 
     }
 
     }
 
}</code>
 
}</code>
FirstRunTimeProperty lets me know when was first application run.
+
FirstRunTimeProperty let us know when was first application run.
 
<gallery>
 
<gallery>
 
File:IsolatedStorageRunTime.png|First Run Time
 
File:IsolatedStorageRunTime.png|First Run Time
Line 252: Line 252:
  
 
Good practice is to create a special static class, that would contain all your settings in it, so you can access any property in a program
 
Good practice is to create a special static class, that would contain all your settings in it, so you can access any property in a program
in any time you want, like this:
+
at any time you want:
 
<code csharp>namespace IsolatedStorageSample
 
<code csharp>namespace IsolatedStorageSample
 
{
 
{
Line 267: Line 267:
  
 
{{VersionHint|Versions will be visible from this template when viewed in preview. You can delete this or leave it in the page as it is not displayed in final version}}
 
{{VersionHint|Versions will be visible from this template when viewed in preview. You can delete this or leave it in the page as it is not displayed in final version}}
 
''Add categories below using category selector.''
 

Revision as of 17:07, 9 November 2012

This article explains how to work with IsolatedStorageSettings.

WP Metro Icon File.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Code ExampleTested with
SDK: [1]
Compatibility
Platform(s): Windows Phone 7.5 and 8.0
Windows Phone 8
Windows Phone 7.5
Article
Keywords: IsolatedStorageSettings, Isolated Storage, User Settings-->
Created: jinek (09 Nov 2012)
Last edited: jinek (09 Nov 2012)

Contents

Introduction

IsolatedStorageSettings - is dictionary-like way for permanent storing values in Isolated Storage. All that you have to do to store a value - is provide a key for this value and a value itself. You can store anything you want: user settings, layout information or application state. All settings from IsolatedStorageSettings are accessible after application shutdown and run again. In this tutorial we are going to create a simple application that keeps one boolean value and then we will extend it for more convenient use.

Basic Sample

  1. Run Visual Studio 2012
  2. Create new Windows Phone project (7.5 or 8.0)
  3. Navigate to MainPage.xaml and replace all control content with one checkbox:
    <phone:PhoneApplicationPage x:Class="IsolatedStorageSample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}">
    <CheckBox Content="Switch option"
    Name="chck"
    Checked="chck_Checked"
    Unchecked="chck_Unchecked"
    VerticalAlignment="Top" />
    </phone:PhoneApplicationPage>
  4. Navigate to MainPage.xaml.cs and add code that does the actual work:
    using System.IO.IsolatedStorage;
    using System.Windows;
     
    namespace IsolatedStorageSample
    {
    public partial class MainPage
    {
    /// <summary>
    /// Object for sync access to IsolatedStorage
    /// </summary>
    private readonly object _sync = new object();
     
    private const string SwitchKeyName = "switch";
     
    // Constructor
    public MainPage()
    {
    InitializeComponent();
    //checking if property exists, if no - create it
    if (!IsolatedStorageSettings.ApplicationSettings.Contains(SwitchKeyName))
    {
    IsolatedStorageSettings.ApplicationSettings[SwitchKeyName] = true;
    SaveSettings();
    }
     
    //the checkbox state initializing
    chck.IsChecked = (bool) IsolatedStorageSettings.ApplicationSettings[SwitchKeyName];
    }
     
    private void chck_Checked(object sender, RoutedEventArgs e)
    {
    IsolatedStorageSettings.ApplicationSettings[SwitchKeyName] = true;
    SaveSettings();
    }
     
    private void chck_Unchecked(object sender, RoutedEventArgs e)
    {
    IsolatedStorageSettings.ApplicationSettings[SwitchKeyName] = false;
    SaveSettings();
    }
     
    /// <summary>
    /// Saving settings to isolated storage
    /// </summary>
    private void SaveSettings()
    {
    lock (_sync)
    {
    IsolatedStorageSettings.ApplicationSettings.Save();
    }
    }
    }
    }
  5. Run the application

You might see the checkbox which after launch can remember his last state before application shutdown.

IsolatedStorageSettings is easy to use. But if you are going to have more then just one setting-value - syncing, keeping key name, checking if setting exists and saving each time it been updated may become a headache. Better way is to implement all this functionality in helper class only once.

Improvement

Easier way to work with IsolatedStorageSettings is to create a wrapper class around it. It would save the setting every time we update it (in a thread safe maner), it would automatically set default value if setting does not exist and finally it would keep the key name - we have to provide it only once during property declaration. Create two new classes:

using System.IO.IsolatedStorage;
 
namespace IsolatedStorageSample
{
/// <summary>
/// Helper class is needed because IsolatedStorageProperty is generic and
/// can not provide singleton model for static content
/// </summary>
internal static class IsolatedStoragePropertyHelper
{
/// <summary>
/// We must use this object to lock saving settings
/// </summary>
public static readonly object ThreadLocker = new object();
 
public static readonly IsolatedStorageSettings Store = IsolatedStorageSettings.ApplicationSettings;
}
 
/// <summary>
/// This is wrapper class for storing one setting
/// Object of this type must be single
/// </summary>
/// <typeparam name="T">Any serializable type</typeparam>
public class IsolatedStorageProperty<T>
{
private readonly object _defaultValue;
private readonly string _name;
private readonly object _syncObject = new object();
 
public IsolatedStorageProperty(string name, T defaultValue = default(T))
{
_name = name;
_defaultValue = defaultValue;
}
 
/// <summary>
/// Determines if setting exists in the storage
/// </summary>
public bool Exists
{
get { return IsolatedStoragePropertyHelper.Store.Contains(_name); }
}
 
/// <summary>
/// Use this property to access the actual setting value
/// </summary>
public T Value
{
get
{
//If property does not exist - initializing it using default value
if (!Exists)
{
//Initializing only once
lock (_syncObject)
{
if (!Exists) SetDefault();
}
}
 
return (T) IsolatedStoragePropertyHelper.Store[_name];
}
set
{
IsolatedStoragePropertyHelper.Store[_name] = value;
Save();
}
}
 
private static void Save()
{
lock (IsolatedStoragePropertyHelper.ThreadLocker)
{
IsolatedStoragePropertyHelper.Store.Save();
}
}
 
public void SetDefault()
{
Value = (T) _defaultValue;
}
}
}

You can extend this classes as you want (may be you want to save values only when application is shutting down?) or you can just copy this classes to your project and start working right now. Using this class is easier then IsolatedStorageSettings:

namespace IsolatedStorageSample
{
using System.Windows;
 
public partial class MainPage
{
//Setting declaration
static readonly IsolatedStorageProperty<bool> SwitchProperty = new IsolatedStorageProperty<bool>("switch",true);
 
public MainPage()
{
InitializeComponent();
chck.IsChecked = SwitchProperty.Value;
}
private void chck_Checked(object sender, RoutedEventArgs e)
{
SwitchProperty.Value = true;
}
 
private void chck_Unchecked(object sender, RoutedEventArgs e)
{
SwitchProperty.Value = false;
}
}
}

See? We still have only one setting but a lot of lines are gone! - With ten or more property-settings this class become indispensable. Lets create another setting - FirstRunTimeProperty:

using System;
 
namespace IsolatedStorageSample
{
using System.Windows;
 
public partial class MainPage
{
static readonly IsolatedStorageProperty<bool> SwitchProperty = new IsolatedStorageProperty<bool>("switch",true);
 
/// <summary>
/// Keeps first run time
/// </summary>
static readonly IsolatedStorageProperty<DateTime> FirstRunTimeProperty = new IsolatedStorageProperty<DateTime>("firstruntime", DateTime.Now);
 
public MainPage()
{
InitializeComponent();
chck.IsChecked = SwitchProperty.Value;
Loaded+=OnLoaded;
}
 
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
//MessageBox.Show - could freeze main thread for a long time
//Dont let it freeze the constructor
MessageBox.Show(FirstRunTimeProperty.Value.ToString());
//This MessageBox always shows time of first run
}
 
private void chck_Checked(object sender, RoutedEventArgs e)
{
SwitchProperty.Value = true;
}
 
private void chck_Unchecked(object sender, RoutedEventArgs e)
{
SwitchProperty.Value = false;
}
}
}

FirstRunTimeProperty let us know when was first application run.

You can run the application two or more times to test it.

Good practice is to create a special static class, that would contain all your settings in it, so you can access any property in a program at any time you want:

namespace IsolatedStorageSample
{
public static class SettingsContainer
{
public static readonly IsolatedStorageProperty<bool> TestProperty1
= new IsolatedStorageProperty<bool>("TestProperty1");
public static readonly IsolatedStorageProperty<string> TestProperty2
= new IsolatedStorageProperty<string>("TestProperty2", "This is a test property");
//...
}
}

The "platform categories" will be displayed here in preview only - Copy paste relevant categories into text here

Version Hint

Windows Phone: [[Category:Windows Phone]]
[[Category:Windows Phone 7.5]]
[[Category:Windows Phone 8]]

Nokia Asha: [[Category:Nokia Asha]]
[[Category:Nokia Asha Platform 1.0]]

Series 40: [[Category:Series 40]]
[[Category:Series 40 1st Edition]] [[Category:Series 40 2nd Edition]]
[[Category:Series 40 3rd Edition (initial release)]] [[Category:Series 40 3rd Edition FP1]] [[Category:Series 40 3rd Edition FP2]]
[[Category:Series 40 5th Edition (initial release)]] [[Category:Series 40 5th Edition FP1]]
[[Category:Series 40 6th Edition (initial release)]] [[Category:Series 40 6th Edition FP1]] [[Category:Series 40 Developer Platform 1.0]] [[Category:Series 40 Developer Platform 1.1]] [[Category:Series 40 Developer Platform 2.0]]

Symbian: [[Category:Symbian]]
[[Category:S60 1st Edition]] [[Category:S60 2nd Edition (initial release)]] [[Category:S60 2nd Edition FP1]] [[Category:S60 2nd Edition FP2]] [[Category:S60 2nd Edition FP3]]
[[Category:S60 3rd Edition (initial release)]] [[Category:S60 3rd Edition FP1]] [[Category:S60 3rd Edition FP2]]
[[Category:S60 5th Edition]]
[[Category:Symbian^3]] [[Category:Symbian Anna]] [[Category:Nokia Belle]]

1276 page views in the last 30 days.