Click here to Skip to main content
Licence CPOL
First Posted 2 Mar 2004
Views 74,381
Downloads 216
Bookmarked 55 times

AppSettings Implementation for Compact Framework

By | 23 Mar 2004 | Article
Learn how to create a settings class that will make it easy to access and store your application settings.

Sample Image - SaveSettings.jpg

Introduction

The .NET Compact Framework does not contain an AppSettings class like the full framework. On the full .NET Framework a developer could gain access to settings stored in the App.Config file by creating a name value collection from the System.Configuration.ConfigurationSettings.AppSettings class. As an advocate of uniformity, I wanted to create something that had similar functionality on the Compact Framework. This article will show you what I came up with.

Using the code

My first step was to create an XML file that looked a lot like the App.Config file in .NET.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="ServerIP" value="192.168.5.22" />
        <add key="UserName" value="testuser" />
        <add key="Password" value="jdhs822@@*" />
        <add key="PhoneNumber" value="5555555555" />
        <add key="TimeOut" value="60" />
        <add key="LastTransmit" value="03/03/2004 9:12:33 PM" />
        <add key="DatabasePath" value="\Program Files\DB\test.sdf" />
    </appSettings>
</configuration>

I named this file Settings.xml and added it to my project with a build action of content. This ensures that the file will get downloaded to my program's executing folder.

My next step was to create a new class called Settings. This class contains only static members so the settings are accessed from the file only once during program execution and the entire program will have easy access to these values.

I wanted the settings to be loaded as soon as the settings were accessed, so I created a static constructor and placed my XML parsing code inside the constructor.

m_settings is a NameValueCollection that stores all of the settings.

public class Settings
{
    private static NameValueCollection m_settings;
    private static string m_settingsPath;

    // Static Ctor
    static Settings()
    {
        // Get the path of the settings file.
        m_settingsPath = Path.GetDirectoryName(
        System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
        m_settingsPath += @"\Settings.xml";

        if(!File.Exists(m_settingsPath))
            throw new FileNotFoundException(
                              m_settingsPath + " could not be found.");

        System.Xml.XmlDocument xdoc = new XmlDocument();
        xdoc.Load(m_settingsPath);
        XmlElement root = xdoc.DocumentElement;
        System.Xml.XmlNodeList nodeList = root.ChildNodes.Item(0).ChildNodes;

        // Add settings to the NameValueCollection.
        m_settings = new NameValueCollection();
        m_settings.Add("ServerIP", nodeList.Item(0).Attributes["value"].Value);
        m_settings.Add("UserName", nodeList.Item(1).Attributes["value"].Value);
        m_settings.Add("Password", nodeList.Item(2).Attributes["value"].Value);
        m_settings.Add("PhoneNumber",
                                  nodeList.Item(3).Attributes["value"].Value);
        m_settings.Add("TimeOut", nodeList.Item(4).Attributes["value"].Value);
        m_settings.Add("LastTransmit",
                                  nodeList.Item(5).Attributes["value"].Value);
        m_settings.Add("DatabasePath",
                                  nodeList.Item(6).Attributes["value"].Value);
    }
}

Now, we need some public accessors to retrieve the values from the NameValueCollection.

public static string ServerIP
{
    get { return m_settings.Get("ServerIP"); }
    set { m_settings.Set("ServerIP", value); }
}

public static string UserName
{
    get { return m_settings.Get("UserName"); }
    set { m_settings.Set("UserName", value); }
}

// ... And so on

The only thing left to do is to add a method for updating our settings. The XmlTextWriter class provides us with a light-weight mechanisim for writing xml to a FileStream. We iterate through the NameValueCollection and create the settings in xml.

public static void Update()
{
    XmlTextWriter tw = new XmlTextWriter(m_settingsPath,
                                       System.Text.UTF8Encoding.UTF8);
    tw.WriteStartDocument();
    tw.WriteStartElement("configuration");
    tw.WriteStartElement("appSettings");

    for(int i=0; i<m_settings.Count; ++i)
    {
        tw.WriteStartElement("add");
        tw.WriteStartAttribute("key", string.Empty);
        tw.WriteRaw(m_settings.GetKey(i));
        tw.WriteEndAttribute();

        tw.WriteStartAttribute("value", string.Empty);
        tw.WriteRaw(m_settings.Get(i));
        tw.WriteEndAttribute();
        tw.WriteEndElement();
    }

    tw.WriteEndElement();
    tw.WriteEndElement();

    tw.Close();
}

Now we can easily access our settings from anywhere in our application!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

pbrooks

Software Developer (Senior)

United States United States

Member

Check out my blog! http://www.pagebrooks.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 3 Pinmemberb0bi21:01 21 Jun '11  
GeneralDid exactly what it should PinmemberBernhard22:46 11 Mar '10  
GeneralMy vote of 1 PinmemberNedyalko Zhekov11:22 19 Jan '10  
QuestionLittle problem PinmemberMember #35281566:29 16 Mar '07  
GeneralAccess Violation Error Pinmemberr20j0:18 30 Nov '05  
GeneralVery Useful PinmemberPaul Baker10:54 18 Aug '05  
GeneralXML File is not being copied over Pinmemberjfaubey2000@yahoo.com8:42 21 Jul '05  
GeneralRe: XML File is not being copied over Pinmemberzero_joker6:27 20 Nov '06  
GeneralRe: XML File is not being copied over PinmemberAgha.net11:44 20 Sep '07  
Generaltiny improvement Pinmemberflair21:33 6 Apr '05  
GeneralRe: tiny improvement Pinmemberflair21:34 6 Apr '05  
GeneralRe: tiny improvement Pinmemberflair21:36 6 Apr '05  
GeneralSystem.NullReferenceException Pinmemberwannafly7:36 12 Apr '04  
GeneralAny chance you could port it to VB PinmemberGeovani5:56 5 Apr '04  
GeneralRe: Any chance you could port it to VB Pinmembercyn3rgy0:45 14 Sep '10  
GeneralA misprint PinsussAlexey Mochalov20:47 21 Mar '04  
GeneralRe: A misprint Pinmemberpbrooks4:07 22 Mar '04  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120528.1 | Last Updated 24 Mar 2004
Article Copyright 2004 by pbrooks
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid