Simple XNA Cross Platform Settings Manager

25. January 2011 12:50 by gogman in Development  //  Tags: , , ,   //   Comments (0)

One of the joys of doing XNA development is the ability to do cross-platform applications quite easily. I must admit I am really enjoying being able to reuse 99% of my code on the PC, XBox, and Windows Phone 7.

One of the common things all applications need, regardless of platform, is a way to persist application settings between application runs. While there are built-in features and many open source libraries available to persist application settings, I found that most were overkill for what I needed.

For me, a simple static class the exposes settings as a series of properties on an object are all I really need.

I present my simple SettingsManager.

This class uses IsolatedStorage on all platforms and requires no special permissions to read and write the settings file. It literally is a drop-in solution for persisting your applications settings.

It exposes only two methods:

  • LoadSettings
  • SaveSettings

It also exposes one object that contains your applications settings:

  • Settings

This class is very simple to use. Simply call LoadSettings in your application constructor and then you have access to all your application settings – even on the first run of your application. Any time you change a setting, simply call SaveSettings. Since the class is static, you have access to all of your settings from anywhere in the application which I find helps simplify the code I write since the application settings are now just essentially global variables.

All you need to do to adapt this for your app is simply change the namespace and modify the AppSettings class to contain the properties you wish to persist. Also don’t forget to set the defaults for those properties in the AppSettings class initializer. Setting the defaults is very important as these are the values your application will see when the settings file is initialized.

Ok, enough talk – here’s the code.

#region usings
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
#endregion
 
namespace YourNamespace
{
 
  #region application settings
 
  public class AppSettings
  {
 
    public bool HasRunOnce { get; set; }
    public bool IsFullScreen { get; set; }
    public bool EnableMusic { get; set; }
    public bool EnableSfx { get; set; }
 
    public AppSettings()
    {
      // Create our default settings
      HasRunOnce = true;
      EnableMusic = true;
      EnableSfx = true;
 
      // Since this is cross platform, you can decide what default values to use for a platform.
      // In the case of full screen, phones and XBoxes are always full screen.
      // In the phone an XBox applications, we don't let the user change this setting.
#if WINDOWS
      IsFullScreen = false;
#else
IsFullScreen = true;
#endif
 
    }
  }
 
  #endregion
 
 
  #region settings manager
 
  static class SettingsManager
  {
 
    private static string fileName = "settings.xml";
    public static AppSettings Settings = new AppSettings();
 
 
    public static void LoadSettings()
    {
      // Create our exposed settings class. This class gets serialized to load/save the settings.
      Settings = new AppSettings();
      //Obtain a virtual store for application
#if WINDOWS
      IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForDomain();
#else
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
#endif
      // Check if file is there
      if (fileStorage.FileExists(fileName))
      {
        XmlSerializer serializer = new XmlSerializer(Settings.GetType());
        StreamReader stream = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.Open, fileStorage));
        try
        {
          Settings = (AppSettings)serializer.Deserialize(stream);
          stream.Close();
        }
        catch
        {
          // An error occurred so let's use the default settings.
          stream.Close();
          Settings = new AppSettings();
          // Saving is optional - in this sample we assume it works and the error is due to the file not being there.
          SaveSettings();
          // Handle other errors here
        }
      }
      else
      {
        SaveSettings();
      }
    }
 
 
    public static void SaveSettings()
    {
      //Obtain a virtual store for application
#if WINDOWS
      IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForDomain();
#else
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
#endif
      XmlSerializer serializer = new XmlSerializer(Settings.GetType());
      StreamWriter stream = new StreamWriter(new IsolatedStorageFileStream(fileName, FileMode.Create, fileStorage));
      try
      {
        serializer.Serialize(stream, Settings);
      }
      catch
      {
        // Handle your errors here
      }
      stream.Close();
    }
 
  }
 
  #endregion
 
}

Enjoy!

The Bestest Windows Evah!

22. October 2010 18:56 by gogman in Microsoft  //  Tags:   //   Comments (3)

windows-7-logo-pcs

Today is Windows 7 is one year old! Happy birthday and great job Microsoft!

Out of my gaggle of geeks I am usually the guy who has to have his old, dead operating system pried out of his hands.

Being a developer, I really hate upgrading operating systems because it takes so long to get it setup with all the tools I use. This time however, I did something rare for me – I got involved in the Win7 beta and installed it on a second hard drive in my primary laptop. From the install screen on, I knew I was going to ditch XP and Vista and go full Win7 as soon as I could. I had fallen in love.

So, to share the love, I will present you with my 7 (clever, eh?) favorite Win7 features.

7. WINDOWS KEY COMBOS

Windows + left or right arrow snaps the active window to the left or right side of the screen. If you are like me and run multiple monitors, it will snap and move the windows across all your monitors.

Windows + SHIFT + left or right arrow will move the window from monitor to monitor without snapping it to the side or changing it’s size and shape.

Windows + up arrow maximizes the active window. Windows + down arrow minimizes the active window.

Windows + Tab will do the 3D document flip. A nice replacement for ALT + Tab.

6. GOD MODE

This handy feature puts all your OS settings and tasks in one place. It’s a clever implementation that nobody is likely to stumble on. Here’s how to access it:

  1. Create a folder anywhere on your system.
  2. Name that folder GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}
  3. Enjoy!

5. WINDOWS CALCULATOR

It does EVERYTHING. Conversions, statistics, you name it. Check out the view menu on the calculator app for more detail. The calculator really is a gem.

4. LIBRARIES

Microsoft had been struggling to make this concept work in previous versions of Windows. They finally nailed the implementation in Win7.

3. WINDOWS MEDIA PLAYER

It finally works right and the wife and I LOVE the “play to” feature. I really love being able to access my media securely from the Internet as well without having to setup a VPN.

2. THE TASK BAR AND AERO PEEK

Oh how I love the taskbar and the way it combines shortcuts and live apps into a single icon. I wonder how it was that we ever got along with the old taskbar.

 

And my favorite Win7 feature?

1. PERFORMANCE AND RELIABILITY

Win7 just seems to run like butter.  It’s snappy, doesn’t crash, and is just a pleasure to use. After a year plus a few months, I am still in love.

About The Bloggers

gogman

gogmanBorn naked, unable to communicate, walk, or feed himself, Gogman overcame these handicaps to become a technologist, decent open water sailor, pretty darn good cook, husband, cat lover, and mediocre blogger.

Gogman works as the CTO at Atomic Goat Studios, an independent game studio start-up located in Southern California developing games for the PC, XBox 360, and Windows Phone 7.

Member Hawaii Yacht Club

dantwo

dantwoFound in a universe that probably exists, Dantwo prides himself on his ability to use the laws of nature to perform complex tasks; such as operating a keyboard.

A graduate student and teaching assistant by trade, he is also found enjoying games, technology, rudimentary philosophy, and observing the universe.

We miss you Andrew

Recent Comments

Comment RSS