Posts Tagged ‘Silverlight’

.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 Silverlight 4 – Toolkit and Theming

9 Comments

I recently wanted to add a theme from the Silverlight 4 Toolkit, and ran into this runtime error…

12212010122804pm

XamlParseException: Failed to create a ‘System.Type’ from the text ‘input:AutoCompleteBox’.

I was perplexed as I didn’t have an AutoCompleteBox in my project.  It turns out that when you drag a theme from the Toolbox onto the designer, VS2010 doesn’t automatically add all of the references needed(it will add 2).  If you drag a theme from the Toolbox into XAML, VS2010 won’t add ANY references.

It also seems that because themes encompass a majority of controls, there must be a reference for those controls in the project.  After much trial and error, here are the 8 references that will be needed when using a theme from the toolkit:

References

If I removed any of these references, the application would throw a runtime exception similar to the screenshot above.

The “BureauBlack” reference will change depending on the theme that you choose to use in your application.  There is a reference for every theme in the toolkit.

Hope this help out anybody who runs across this problem.

Tags: , ,