MOBILE

Windows Phone 7 Development : Isolated Storage - Working with Isolated Storage Settings

2/26/2011 4:22:15 PM
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.
Figure 1. IsolatedStorageSettingsDemo

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.

Figure 2. Windows Phone Application template for creating IsolatedStorageSettingsDemo

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.

Figure 3. IsolatedStorageSettingsDemo design view

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.

Other  
  •  Mobile Application Security : WebOS Security - Permissions and User Controls
  •  Mobile Application Security : WebOS Security - Code Security
  •  Windows Phone 7 Development : Working with Isolated Directory Storage (part 2)
  •  Windows Phone 7 Development : Working with Isolated Directory Storage (part 1)
  •  iPhone Application Development : Making Multivalue Choices with Pickers - Using Date Pickers (part 3)
  •  iPhone Application Development : Making Multivalue Choices with Pickers - Using Date Pickers (part 2) - Adding a Date Picker
  •  iPhone Application Development : Making Multivalue Choices with Pickers - Using Date Pickers (part 1)
  •  iPhone Application Development : Making Multivalue Choices with Pickers - Understanding Pickers
  •  Sync Your iPad with iTunes : Troubleshooting iTunes and the Sync
  •  Sync Your iPad with iTunes : Manually Transferring Music, Movies, Podcasts, and More on Your iPad (Drag-and-Drop Method)
  •  Windows Phone 7 Development : Internationalization - Using Resource Files to Localize Content
  •  Windows Phone 7 Development : Internationalization - Storing and Retrieving Current Culture Settings
  •  Mobile Application Security : WebOS Security - Development and Security Testing
  •  Mobile Application Security : WebOS Security - Introduction to the Platform
  •  iPhone Application Development : Getting the User’s Attention - Using Alert Sounds and Vibrations
  •  iPhone Application Development : Getting the User’s Attention - Using Action Sheets
  •  jQuery 1.3 : Modifying table appearance (part 4) - Filtering
  •  jQuery 1.3 : Modifying table appearance (part 3) - Collapsing and expanding sections
  •  jQuery 1.3 : Modifying table appearance (part 2) - Tooltips
  •  jQuery 1.3 : Modifying table appearance (part 1) - Row highlighting
  •  
    Top 10
    SQL Server 2008 : Advanced Stored Procedure Programming and Optimization - Installing and Using .NET CLR Stored Procedures
    Windows Server 2008 : DHCP/WINS/Domain Controllers - Understanding the Key Components of an Enterprise Network
    Wireless Threats
    Personalizing Windows 7 (part 6) - Configuring Your Monitors
    Multifaceted Tests : Attempting Command Injection Interactively & Attempting Command Injection Systematically
    Web Security Testing : Manipulating Sessions - Analyzing Session Identifiers with Burp
    Exploring the T-SQL Enhancements in SQL Server 2005 : Common Table Expressions
    Developing an SEO-Friendly Website : Content Management System (CMS) Issues
    Wireless Security in Windows Vista
    SharePoint 2010 : Understanding Windows PowerShell Concepts (part 2)
    Most View
    Building a WPF Application without XAML (part 2)
    IIS 7.0 : Managing Configuration - Sharing Configuration Between Servers
    Where Windows Malware Hides
    SQL Server 2008 : Transact-SQL Programming - PIVOT and UNPIVOT
    iPhone 3D Programming : Adding Shaders to ModelViewer (part 1) - New Rendering Engine
    Payload Smuggling
    iPhone Application Development : Implementing a Custom Picker View (part 3) - Reacting to a Picker View Choice
    IIS 7.0 : Configuration File Syntax
    Windows 7 : Keeping Your Family Safe While Using Your Computer (part 1)
    WAP and Mobile HTML Security : Authentication on WAP/Mobile HTML Sites & Encryption
    Exchange Server 2010 : Keep Exchange Healthy (part 2) - Verify Exchange Server Health
    Windows Phone 7 Advanced Programming Model : Advanced Data Binding (part 2) - Syndicated Services
    Windows Phone 7 : Using Accelerometer Data to Move a Ball
    Developing Applications for the Cloud on the Microsoft Windows Azure Platform : DNS Names, Certificates, and SSL in the Surveys Application
    SQL Server 2008 : Using Temporary Tables in Stored Procedures
    Understanding Active Directory Certificate Services (AD CS) in Windows Server 2008 R2
    Windows 7 : Windows Driver Foundation Architecture (part 3) - Driver Frameworks
    Reporting Services with SQL Azure : Creating the Report Design
    Parallel Programming with Microsoft .Net : Dynamic Task Parallelism - An Example
    Using SharePoint Central Administration for Backup and Restore