Posts Tagged ‘wp7dev’

.Net, Windows Phone 7 WP7 – Using IsolatedStorageSettings

0 Comments

In a previous tutorial, I wrote about using the Isolated Storage to store files on a WP7 device. Let’s say that instead of storing data, you wanted to store settings for your application. This where the IsolatedStorageSettings comes in.

The IsolatedStorageSettings is a place to store Key/Value pairs of data.

So let’s say that my application used the Microsoft Ad control, but I wanted to be nice and give the user the ability to turn the ads on and off.

On my Settings screen, I would have a checkbox(AdsCheckbox) for allowing the ads. In code, I would save the value by doing this…

var settings = IsolatedStorageSettings.ApplicationSettings;

if (settings.Contains("AllowAds"))
    settings["AllowAds"] = AdsCheckbox.IsChecked.Value;
else
    settings.Add("AllowAds", AdsCheckbox.IsChecked.Value);

settings.Save();

If you will notice, the ApplicationSettings object does have a method that allows you to check to see if the key already exists in the Settings. An exception will be thrown if you try to add a key that already exists, so it’s necessary to do this check before assigning a value.

Also, as you can see, it’s very easy to get the value out of the settings…

// when the form opens, I want to set the Checkbox to being checked
//   or unchecked depending on the setting
var settings = IsolatedStorageSettings.ApplicationSettings;

if (settings.Contains("AllowAds"))
    AdsCheckbox.IsChecked = bool.Parse(settings["AllowAds"].ToString());

However, the IsolatedStorageSettings class isn’t only for simply datatypes. It can also store your custom class objects.

Employee class

public class Employee
{
    public string FullName { get; set; }
    public decimal Salary { get; set; }
}

Then on my form, I have a button to save an instance of the Employee class to the IsolatedStorageSettings

private void btnSave_Click(object sender, RoutedEventArgs e)
{
    var settings = IsolatedStorageSettings.ApplicationSettings;

    Employee emp = new Employee()
    {
        FullName = "John Doe",
        Salary = 250000
    };

    settings.Add("Employee1", emp);
    settings.Save();
}

I also have a button that will load the object from the IsolatedStorageSettings

private void btnLoad_Click(object sender, RoutedEventArgs e)
{
    var settings = IsolatedStorageSettings.ApplicationSettings;

    Employee emp;

    if (settings.TryGetValue<Employee>("Employee1", out emp))
    {
         MessageBox.Show(string.Format("Full Name: {0}\nSalary: {1:c}", emp.FullName, emp.Salary));
    }
}

Notice that the IsolatedStorageSettings.ApplicationSettings class also has the TryGetValue method. This method behaves exactly like the TryParse methods of the .Net datatypes. It will return a boolean specifying whether the key was found and whether the conversion from object –> Employee was successful. If it’s successful, it will return the instance as the out parameter.

After running the application, clicking the Save button, then clicking the Load button, we will get this message box…

2

Tags: , , , , ,

.Net, Windows Phone 7 WP7 – Working With Isolated Storage

1 Comment

In this tutorial, I will demonstrate how to work with Isolated Storage in Windows Phone 7. This is going to be a very simple tutorial where we create a text file and write data to it. We will then read that data and append more data to it.

So first, we need to add these using statements to the top of the code(if they aren’t already there):

using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;

Next we will have our form. Very basic. It has two Textboxes and a Button. The first TextBox will allow the user to type in some text. The Button will save the data to IsolatedStorage, then read the data from the file and put it into the second TextBox.

Here is the XAML:

<Grid x:Name="ContentGrid" Grid.Row="1">

    <TextBox
        Name="txtText"
        Height="128"
        HorizontalAlignment="Left"
        Margin="8,71,0,0"
        VerticalAlignment="Top"
        Width="460"
        TextWrapping="Wrap"
        FontSize="16" />

    <Button
        Name="btnSave"
        Content="Save"
        Click="btnSave_Click"
        Height="115"
        HorizontalAlignment="Left"
        Margin="62,203,0,0"
        VerticalAlignment="Top"
        Width="336" />

    <TextBlock
        Name="textBlock1"
        Text="Text to add to file:"
        Height="30"
        HorizontalAlignment="Left"
        Margin="24,49,0,0"
        VerticalAlignment="Top" />

    <TextBlock
        Name="textBlock2"
        Text="Data currently in file:"
        Height="30"
        HorizontalAlignment="Left"
        Margin="24,342,0,0"
        VerticalAlignment="Top" />

    <TextBox
        Name="txtCurrentText"
        Height="128"
        HorizontalAlignment="Left"
        Margin="6,364,0,0"
        VerticalAlignment="Top"
        Width="460"
        TextWrapping="Wrap"
        FontSize="16" />

</Grid>

So now we move to the code. We need to create an IsolatedStorageFile object:

using (var isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
{

}

Since we will always be appending to the file, we need to check to make sure the file exists. If it doesn’t exist, we need to create it.

// we need to check to see if the file exists
if (!isoStorage.FileExists(fileName))
{
    // file doesn't exist...time to create it.
    isoStorage.CreateFile(fileName);
}

Once we have done the FileExists check, we can now open the file. Once the file has been opened, we can now use the StreamWriter class to write to it.

// since we are appending to the file, we must use FileMode.Append
using (var isoStream = new IsolatedStorageFileStream(fileName, FileMode.Append, isoStorage))
{
    // opens the file and writes to it.
    using (var fileStream = new StreamWriter(isoStream))
    {
        fileStream.WriteLine(txtText.Text);
    }
}

Note: notice that we opened the file using FileMode.Append. Because we used this mode, we can’t read from the file, we can only write to it.

So to read from the file, we will need to open the file again, this time using FileMode.Open. We are going to do this in another using block. Once the file is opened, we use the StreamReader class to read it.

// you cannot read from a stream that you opened in FileMode.Append.  Therefore, we need
//   to close the IsolatedStorageFileStream then open it again in a different FileMode.  Since we
//   we are simply reading the file, we use FileMode.Open
using (var isoStream = new IsolatedStorageFileStream(fileName, FileMode.Open, isoStorage))
{
    // opens the file and reads it.
    using (var fileStream = new StreamReader(isoStream))
    {
        txtCurrentText.Text = fileStream.ReadToEnd();
    }
}

And that’s it. If you run the application, type in the first textbox, hit Save, the data will show up in the bottom textbox. Do it again, and you will see that it has appended to the file.

As you can see, writing to Isolated Storage is really easy.

Here is the entire code for the form…

using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using Microsoft.Phone.Controls;

namespace WP7IsoStorageDemo
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            string fileName = "MyTextfile.txt";

            using (var isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // we need to check to see if the file exists
                if (!isoStorage.FileExists(fileName))
                {
                    // file doesn't exist...time to create it.
                    isoStorage.CreateFile(fileName);
                }

                // since we are appending to the file, we must use FileMode.Append
                using (var isoStream = new IsolatedStorageFileStream(fileName, FileMode.Append, isoStorage))
                {
                    // opens the file and writes to it.
                    using (var fileStream = new StreamWriter(isoStream))
                    {
                        fileStream.WriteLine(txtText.Text);
                    }
                }

                // you cannot read from a stream that you opened in FileMode.Append.  Therefore, we need
                //   to close the IsolatedStorageFileStream then open it again in a different FileMode.  Since we
                //   we are simply reading the file, we use FileMode.Open
                using (var isoStream = new IsolatedStorageFileStream(fileName, FileMode.Open, isoStorage))
                {
                    // opens the file and reads it.
                    using (var fileStream = new StreamReader(isoStream))
                    {
                        txtCurrentText.Text = fileStream.ReadToEnd();
                    }
                }
            }
        }
    }
}
Tags: , , , ,

.Net, Silverlight, Windows Phone 7 WP7 – Using the ToggleSwitch

1 Comment

This will be the first of a number of posts highlighting the new controls that have been added to the WP7 Toolkit.  It’s a really great set of tools that makes life easier for us developers.

Download WP7 Toolkit

So the first control I am going to talk about is the ToggleSwitch control.  It’s a control that resembles a lightswitch and is a nice was of showing an On/Off or True/False setting instead of using a plain checkbox.

So let’s create a Windows Phone 7 project called ToggleSwitchDemo.

Open the Toolbox and find the ToggleSwitch control.  If it’s not listed, right-click on the Toolbox –> Choose Items –> then scroll down until you find the ToggleSwitch control in the list.

Once the control is in the Toolbox, drag it onto the page.  By default, it will look like this….

11-14-2010 10-21-33 AM

Run the application using F5, then click on the ToggleSwitch.  It will change from Off to On.

11-14-2010 10-24-16 AM 11-14-2010 10-24-28 AM

There are a number of options that are available for the text for the ToggleControl.  The Header property will change the heading of the control.  The Content property will set the content of the control(On/Off).

In one of my application, I used the ToggleSwitch to allow the user to turn on/off Ads that I have in the app.  So for me, I changed the Header to “Ads”, and since I default the ToggleSwitch to being On(IsChecked is True), I set the Content to “Ads are enabled.

The ToggleSwitch also allows you to handle when the control is checked and unchecked.  So here is how my ToggleSwitch would look in XAML

<toolkit:ToggleSwitch
    Name="AdsToggleSwitch"
    Header="Ads"
    Content="Ads are enabled"
    Height="111"
    HorizontalAlignment="Left"
    Margin="1,197,0,0"
    VerticalAlignment="Top"
    Width="456"
    IsChecked="True"
    Checked="AdsToggleSwitch_Checked"
    Unchecked="AdsToggleSwitch_Unchecked" />

Then the code for the Checked and Unchecked events…

private void AdsToggleSwitch_Checked(object sender, RoutedEventArgs e)
{
     AdsToggleSwitch.Content = "Ads are enabled";
}

private void AdsToggleSwitch_Unchecked(object sender, RoutedEventArgs e)
{
     AdsToggleSwitch.Content = "Ads are disabled";
}

Now my control would look like this…

11-14-2010 10-41-21 AM 11-14-2010 10-41-30 AM

The ToggleSwitch is a great control that allows your app to keep the “Metro” look and feel that a plain CheckBox wouldn’t allow you to do without custom coding.

Tags: , , ,