In this section, you'll build an application that demonstrates CRUD operation (create, read, update, and delete) of System.IO.IsolatedStorage.IsolatedStorageSettings. We've named it IsolatedStorageSettingsDemo. Figure 1 shows how its UI will look on a Windows Phone.
In the IsolatedStorageSettingsDemo application, as shown in Figure 1, when the Save button is clicked, the value in the "Value" text box will be added to the isolated storage settings using the key in the "Key"
text box. Whenever new key-value pair data is added to the isolated
storage settings, the key will be added to the list box of keys. When
any of the keys in the list box of keys is selected, the "Key" text box and the "Value"
text box will be populated with the data retrieved from the isolated
storage settings. The Delete button will delete the selected key from
the isolated storage settings.
To build the demo, you'll
first create a new project, then add XAML markup to create a new main
page and its controls. Finally, you'll add behavior to the application
with C# code that makes use of isolated storage APIs to save and
retrieve key-value pairs.
1. Creating a New Project
To create the new IsolatedStorageSettingsDemo project, open Microsoft Visual Studio 2010 Express for Windows Phone. Select File =>
New Project on the Visual Studio menu, select the Windows Phone
Application template on the New Project dialogue, name the application
"IsolatedStorageSettingsDemo," and click OK, as shown in Figure 2.
Now you'll build the application main page.
2. Building the Application UI (XAML)
To create the UI for IsolatedStorageSettingsDemo, go to Solution Explorer, open MainPage.xaml, and replace XAML with the following chunks of XAML markup in the sequence shown.
2.1. Selecting the UI Resources
The following code identifies
where to find the UI controls that will be used to build this main page
for this application. Using the namespace xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
will allow you to add common Windows Phone controls like text boxes,
buttons, and list boxes, which will be used to create the main page.
Also we are adding a reference to a code-behind class (x:Class="IsolatedStorageSettingsDemo.MainPage") that will handle the main page controls' events.
<phone:PhoneApplicationPage
x:Class="IsolatedStorageSettingsDemo.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"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
shell:SystemTray.IsVisible="True">
2.2. Building the Main Page and Adding Controls
Now add the various controls and layouts you need to create the UI shown in Figure 13-5.
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneBackgroundBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitleGrid is the name of the application and page title-->
<Grid x:Name="TitleGrid" Grid.Row="0">
<TextBlock Text="Isolated Storage Settings Demo"
x:Name="textBlockListTitle"
Style="{StaticResource PhoneTextTitle1Style}"
FontSize="30" />
</Grid>
<!--ContentGrid is empty. Place new content here-->
<Grid x:Name="ContentGrid" Grid.Row="1">
<TextBox Height="72" HorizontalAlignment="Left"
Margin="172,46,0,0" Name="txtKey" Text=""
VerticalAlignment="Top" Width="212" />
<Button Content="Save" Height="70"
HorizontalAlignment="Left" Margin="78,228,0,0"
Name="btnSave" VerticalAlignment="Top" Width="160"
Click="btnSave_Click" />
<ListBox Height="168" HorizontalAlignment="Left" Margin="94,392,0,0"
Name="lstKeys" VerticalAlignment="Top" Width="274"
BorderThickness="1" SelectionChanged="lstKeys_SelectionChanged" />
<TextBlock Height="39" HorizontalAlignment="Left" Margin="94,62,0,0"
Name="textBlock1" Text="Key" VerticalAlignment="Top" />
<TextBox Height="74" HorizontalAlignment="Left" Margin="172,124,0,0"
Name="txtValue" Text="" VerticalAlignment="Top" Width="212" />
<TextBlock Height="39" HorizontalAlignment="Left" Margin="94,140,0,0"
Name="textBlock2" Text="Value" VerticalAlignment="Top" />
<Button Content="Delete" Height="70" HorizontalAlignment="Left"
Margin="224,228,0,0" Name="btnDelete" VerticalAlignment="Top"
Width="160" Click="btnDelete_Click" />
<TextBlock Height="39" HorizontalAlignment="Left" Margin="94,347,0,0"
Name="textBlock3" Text="List of Keys" VerticalAlignment="Top" />
</Grid>
</Grid>
</phoneNavigation:PhoneApplicationPage>
Once you've added the XAML markup blocks displayed in this section to MainPage.xaml, you should see the UI shown on the Visual Studio Design View tab in Figure 3.
Now it's time to add behavior to the application.
3. Coding Application Behavior (C#)
From Solution Explorer, open MainPage.xaml.cs and replace the code you find there with the following blocks of C# code.
3.1. Specifying the Namespaces
Begin by listing the namespaces the application will use. Notice our inclusion of System.IO.IsolatedStorage in order to work with the isolated storage settings.
using System;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
namespace IsolatedStorageSettingsDemo
{
public partial class MainPage : PhoneApplicationPage
{
private IsolatedStorageSettings _appSettings;
3.2. Initializing the Application
Now add the next code block to the MainPage class. Notice the use of the BindKeyList()
method, which will retrieve all keys from the isolated storage settings
and bind them to the list box created in the previous section.
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait;
_appSettings = IsolatedStorageSettings.ApplicationSettings;
BindKeyList();
}
3.3. Adding the Save Button Event Handler
Now add an event handler for the Save button. When the Save
button is clicked, the application reads the key and the value from
user-inputted text boxes into the isolated storage settings.
// Handles Create and Update
// If the key does not exist key-value pair will be added
// ElseIf the key exists the value will be updated
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(txtKey.Text))
{
if (_appSettings.Contains(txtKey.Text))
{
_appSettings[txtKey.Text] = txtValue.Text;
}
else
{
_appSettings.Add(txtKey.Text, txtValue.Text);
}
_appSettings.Save();
BindKeyList();
}
}
NOTE
An isolated storage
file will perform much better than isolated storage settings because a
file can be streamed in and out of the isolated storage file as raw data
by using StreamWriter and StreamReader,
whereas the storage and retrieval of data in an isolated storage
settings key-value pair dictionary require serialization. However, there
is complexity in using isolated storage files, where you need to use
the file stream to save and retrieve the data and must be careful to
dispose the stream after each use, whereas in the isolated storage
settings, there is inherent simplicity in using the key to save and
retrieve the data.
3.4. Adding the Delete Button Event Handler
Next, add an event handler for
the Delete button. When the Delete button is clicked, we remove the
selected key from the isolated storage settings and rebind the list box.
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
if (lstKeys.SelectedIndex > −1)
{
_appSettings.Remove(lstKeys.SelectedItem.ToString());
_appSettings.Save();
BindKeyList();
}
}
3.5. Adding the Listbox Changed Event
Finally, you'll use the Listbox
changed event to update the Key and Value text boxes of the application
interface. When the user selects a key from the list box, the
application will load the key and its associated value from the isolated
storage settings using the selected key and then populate the key and
value text boxes.
// When key is selected value is retrieved from the storage settings
private void lstKeys_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
string key = e.AddedItems[0].ToString();
if (_appSettings.Contains(key))
{
txtKey.Text = key;
txtValue.Text = _appSettings[key].ToString();
}
}
}
private void BindKeyList()
{
lstKeys.Items.Clear();
foreach (string key in _appSettings.Keys)
{
lstKeys.Items.Add(key);
}
txtKey.Text = "";
txtValue.Text = "";
}
}
}
3.6. Testing the Finished Application
To test the finished application, press F5. The result should resemble the screenshot shown in Figure 1.