Posts Tagged ‘C#’

.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 C# – Get Windows Mobile Theme Color

1 Comment

I recently had a business requirement to color the background of a TextBox in Windows Mobile to a specific color.  After completing the tasks, I noticed that the color that was chosen(blue) didn’t look right on devices that used a different theme like red or green.  So I decided to figure out how to set the background color to match the theme color.

The theme system colors are located in the registry entry HKLM\System\GWE\SysColor.  This registry entry is a BLOB that contains 29 DWORD values that correspond to the different colors of the theme.

For my application, I decided to use the color of the title bar of active windows.  This color is normally the dominate color of the theme.  This color is the third DWORD value in the registry entry.

Each DWORD value in the registry entry is a 4 byte HEX value that corresponds to a specific color.  The first byte is the RED value, second value is the GREEN value, third value is the BLUE value, and the fourth value is always 0.

For this code, I used the OpenNetCF framework to get the registry values.

/// <summary>
/// Gets the theme color
/// </summary>
/// <returns> Returns a Color or null</returns>
public Color? GetThemeColor()
{
    try
    {
         // gets the registry key
         RegistryKey keyColor = Registry.LocalMachine.OpenSubKey(@"System\GWE");

         // keyColor will be null if registry key was not found
         if (keyColor == null)
             return null;

        byte[] data = (byte[])keyColor.GetValue("SysColor");

        if (data[8] != 0 && data[9] != 0 && data[10] != 0)
        {
             // the third set of values is for the color of the
             //    title bar of an active window.
             int red = Convert.ToInt32(data[8]);
             int green = Convert.ToInt32(data[9]);
             int blue = Convert.ToInt32(data[10]);

             return Color.FromArgb(red, green, blue);
        }

        return null;
    }
    catch
    {
         return null;
    }
}

Usage is pretty simple for the method…

Color? themeColor = GetThemeColor();

if(themeColor != null)
   txtComments.BackColor = themeColor;
Tags: , ,