An Easy .NET CF Settings Class

written by jasonrshaver on Wednesday, March 11 2009

Every time I start a new Windows Mobile project, I find myself needing a new 'Settings' class.  This is the one that I have been using for many of my projects, here are some of its features:

  • Simple Key/Value pair usage
  • You can select wether to save using an XML file or registry by Key
  • Supports Int, Bool, and String
  • Can hold settings on the file system using the filename "MyApplication.exe.config"
  • Can hold settings in the registry using the path "HKLM/Software/MyApplication.exe/"
  • Fast read caching for file settings

As a note, you can't use GetEntryAssembly in the .NET Compact Framework to find the name of the launching executable, so instead I am using the GetModuleFileName from CoreDll.

Here is the code, if you find anything I can do better, send me an email or leave a comment:

using System;

using System.Data;

using System.IO;

using System.Runtime.InteropServices;

using Microsoft.Win32;

 

namespace ThisNamespace

{

    static public class Settings

    {

        static private DataSet _SettingsDataSet = null;

        static private String _ApplicationName = String.Empty;

        static private String _XmlFile = String.Empty;

        static private String _RegistryPath = String.Empty;

 

        static private DataSet SettingsDataSet

        {

            get

            {

                if (_SettingsDataSet == null)

                {

                    _SettingsDataSet = new DataSet();

                    _SettingsDataSet.Tables.Add(new DataTable("Settings"));

                    _SettingsDataSet.Tables["Settings"].Columns.Add("Key", Type.GetType("System.String"));

                    _SettingsDataSet.Tables["Settings"].Columns.Add("Value", Type.GetType("System.String"));

 

                    if (File.Exists(XmlFile))

                        _SettingsDataSet.ReadXml(XmlFile, XmlReadMode.Auto);

                }

                return _SettingsDataSet;

            }

        }

        static private DataTable SettingsTable

        {

            get

            {

                return SettingsDataSet.Tables["Settings"];

            }

        }

        static private String ApplicationName

        {

            get

            {

                if (String.IsNullOrEmpty(_ApplicationName))

                {

                    byte[] buffer = new byte[520];

                    int ReturnedDataLength = GetModuleFileName(IntPtr.Zero, buffer, buffer.Length);

                    String ApplicationFullName = System.Text.Encoding.Unicode.GetString(buffer, 0, ReturnedDataLength * 2);

                    _ApplicationName = Path.GetFileName(ApplicationFullName);

                }

                return _ApplicationName;

            }

        }

        static private String XmlFile

        {

            get

            {

                if (String.IsNullOrEmpty(_XmlFile))

                    _XmlFile = String.Format(@"{0}.config", ApplicationName);

                return _XmlFile;

            }

        }

        static private String RegistryPath

        {

            get

            {

                if (String.IsNullOrEmpty(_RegistryPath))

                    _RegistryPath = String.Format(@"Software\{0}\Settings", ApplicationName);

                return _RegistryPath;

            }

        }

 

        static public void SaveSetting(string key, bool value)

        {

            SaveSetting(key, value.ToString(), StoreLocation.File);

        }

        static public void SaveSetting(string key, bool value, StoreLocation storeLocation)

        {

            SaveSetting(key, value.ToString(), storeLocation);

        }

        static public void SaveSetting(string key, int value)

        {

            SaveSetting(key, value.ToString(), StoreLocation.File);

        }

        static public void SaveSetting(string key, int value, StoreLocation storeLocation)

        {

            SaveSetting(key, value.ToString(), storeLocation);

        }

        static public void SaveSetting(string key, string value)

        {

            SaveSetting(key, value, StoreLocation.File);

        }

        static public void SaveSetting(string key, string value, StoreLocation storeLocation)

        {

            switch (storeLocation)

            {

                case StoreLocation.File:

                    foreach (DataRow ThisRow in SettingsTable.Rows)

                    {

                        if (ThisRow["Key"].Equals(key))

                        {

                            ThisRow["Key"] = value;

                            _SettingsDataSet.WriteXml(XmlFile);

                            return;

                        }

                    }

                    DataRow NewRow = SettingsTable.NewRow();

                    NewRow["Key"] = key;

                    NewRow["Value"] = value;

                    _SettingsDataSet.WriteXml(XmlFile, XmlWriteMode.IgnoreSchema);

                    return;

                case StoreLocation.Registry:

                    RegistryKey ThisKey = Registry.LocalMachine.OpenSubKey(RegistryPath, true);

                    if (ThisKey == null)

                    {

                        RegistryKey LocalMachineKey = Microsoft.Win32.Registry.LocalMachine;

                        LocalMachineKey.CreateSubKey(RegistryPath);

                        LocalMachineKey.Close();

                        ThisKey = Registry.LocalMachine.OpenSubKey(RegistryPath, true);

                    }

                    ThisKey.SetValue(key, value, RegistryValueKind.String);

                    ThisKey.Close();

                    return;

                default:

                    throw new ArgumentException("Unknown StoreLocation type");

            }

        }

        static public int GetSetting(string key, int defaultValue)

        {

            return GetSetting(key, defaultValue, StoreLocation.File);

        }

        static public int GetSetting(string key, int defaultValue, StoreLocation storeLocation)

        {

            String Result = GetSetting(key, defaultValue.ToString(), storeLocation);

            return int.Parse(Result);

        }

        static public bool GetSetting(string key, bool defaultValue)

        {

            return GetSetting(key, defaultValue, StoreLocation.File);

        }

        static public bool GetSetting(string key, bool defaultValue, StoreLocation storeLocation)

        {

            String Result = GetSetting(key, defaultValue.ToString(), storeLocation);

            return bool.Parse(Result);

        }

        static public string GetSetting(string key, String defaultValue)

        {

            return GetSetting(key, defaultValue, StoreLocation.File);

        }

        static public string GetSetting(string key, String defaultValue, StoreLocation storeLocation)

        {

            switch (storeLocation)

            {

                case StoreLocation.File:

                    foreach (DataRow ThisRow in SettingsTable.Rows)

                    {

                        if (ThisRow["Key"].Equals(key))

                        {

                            return ThisRow["Key"].ToString();

                        }

                    }

                    return defaultValue;

                case StoreLocation.Registry:

                    try

                    {

                        RegistryKey ThisKey = Registry.LocalMachine.OpenSubKey(RegistryPath, false);

                        object Result = ThisKey.GetValue(key, defaultValue);

                        ThisKey.Close();

                        return Result.ToString();

                    }

                    catch

                    {

                        return defaultValue;

                    }

                default:

                    throw new ArgumentException("Unknown StoreLocation type");

            }

        }

 

        [DllImport("coredll.dll", SetLastError = true)]

        static private extern int GetModuleFileName(IntPtr hModule, byte[] lpFilename, int nSize);

 

        public enum StoreLocation

        {

            File = 0,

            Registry = 1,

        }

 

    }

}

Similar Posts

  1. Guidance on using CSLA’s EditableRootList for Management UIs
  2. How Parse XML Using Regular Expressions And C#
  3. View All Icon Sizes With 100% Managed Code

Comments

  • Jordan Duerksen on on 3.11.2009 at 2:36 PM

    Jordan Duerksen avatar

    That looks like a pretty good implementation.

    I think you can use AppDomain.CurrentDomain.FriendlyName to get your executable's filename (without path), but what you have would seem fine as well.

    I was going to suggest looking into Isolated Storage and the System.Runtime.Serialization.SerializationInfo class. But it looks like both of those are not supported in the Compact Framework. Maybe in a later version of .Net CF.

Post a comment

Options:

Size

Colors