Click here to Skip to main content
15,887,477 members
Articles / Mobile Apps

AppSettings Implementation for Compact Framework

Rate me:
Please Sign up or sign in to vote.
4.41/5 (28 votes)
23 Mar 2004CPOL1 min read 117.6K   1.1K   60   18
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
<?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.

C#
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.

C#
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.

C#
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)


Written By
Software Developer (Senior)
United States United States
Check out my blog! http://www.pagebrooks.com

Comments and Discussions

 
SuggestionUse key instead of id Pin
MarownIOM9-Apr-14 6:10
MarownIOM9-Apr-14 6:10 
GeneralMy vote of 3 Pin
b0bi21-Jun-11 21:01
b0bi21-Jun-11 21:01 
GeneralDid exactly what it should Pin
Bernhard11-Mar-10 22:46
Bernhard11-Mar-10 22:46 
GeneralMy vote of 1 Pin
Nedyalko Zhekov19-Jan-10 11:22
Nedyalko Zhekov19-Jan-10 11:22 
QuestionLittle problem Pin
Member 352815616-Mar-07 6:29
Member 352815616-Mar-07 6:29 
GeneralAccess Violation Error Pin
r20j30-Nov-05 0:18
r20j30-Nov-05 0:18 
GeneralVery Useful Pin
Paul Baker18-Aug-05 10:54
Paul Baker18-Aug-05 10:54 
GeneralXML File is not being copied over Pin
jfaubey2000@yahoo.com21-Jul-05 8:42
jfaubey2000@yahoo.com21-Jul-05 8:42 
GeneralRe: XML File is not being copied over Pin
zero_joker20-Nov-06 6:27
zero_joker20-Nov-06 6:27 
GeneralRe: XML File is not being copied over Pin
Agha.net20-Sep-07 11:44
Agha.net20-Sep-07 11:44 
Generaltiny improvement Pin
flair6-Apr-05 21:33
flair6-Apr-05 21:33 
GeneralRe: tiny improvement Pin
flair6-Apr-05 21:34
flair6-Apr-05 21:34 
GeneralRe: tiny improvement Pin
flair6-Apr-05 21:36
flair6-Apr-05 21:36 
GeneralSystem.NullReferenceException Pin
wannafly12-Apr-04 7:36
wannafly12-Apr-04 7:36 
GeneralAny chance you could port it to VB Pin
Geovani5-Apr-04 5:56
Geovani5-Apr-04 5:56 
GeneralRe: Any chance you could port it to VB Pin
cyn3rgy14-Sep-10 0:45
cyn3rgy14-Sep-10 0:45 
Hey Geovani

very late but it might help someone else:

' I had 3 settings, named Analyst, DefaultProject, and DefaultRateDesc.
' You need to modify the m_settings.Add lines and the Get/Set stuff to suit your settings.
' 

Imports System.Collections.Specialized
Imports System.IO
Imports System.Xml

Public Class Settings
    Private Shared m_settings As NameValueCollection
    Private Shared m_settingsPath As String

    ' Static Ctor
    Shared Sub New()
        ' Get the path of the settings file.
        m_settingsPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
        m_settingsPath += "\Settings.xml"

        If Not File.Exists(m_settingsPath) Then
            Throw New FileNotFoundException(m_settingsPath & " could not be found.")
        End If

        Dim xdoc As System.Xml.XmlDocument = New XmlDocument()
        xdoc.Load(m_settingsPath)
        Dim root As XmlElement = xdoc.DocumentElement
        Dim nodeList As System.Xml.XmlNodeList = root.ChildNodes.Item(0).ChildNodes

        ' Add settings to the NameValueCollection.
        m_settings = New NameValueCollection()
        m_settings.Add("Analyst", nodeList.Item(0).Attributes("value").Value)
        m_settings.Add("DefaultProject", nodeList.Item(1).Attributes("value").Value)
        m_settings.Add("DefaultRateDesc", nodeList.Item(2).Attributes("value").Value)
    End Sub
    Public Shared Property Analyst() As String
        Get
            Return m_settings.[Get]("Analyst")
        End Get
        Set(ByVal value As String)
            m_settings.[Set]("Analyst", value)
        End Set
    End Property

    Public Shared Property DefaultProject() As String
        Get
            Return m_settings.[Get]("DefaultProject")
        End Get
        Set(ByVal value As String)
            m_settings.[Set]("DefaultProject", value)
        End Set
    End Property

    Public Shared Property DefaultRateDesc() As String
        Get
            Return m_settings.[Get]("DefaultRateDesc")
        End Get
        Set(ByVal value As String)
            m_settings.[Set]("DefaultRateDesc", value)
        End Set
    End Property
    Public Shared Sub Update()
        Dim tw As New XmlTextWriter(m_settingsPath, System.Text.UTF8Encoding.UTF8)
        tw.WriteStartDocument()
        tw.WriteStartElement("configuration")
        tw.WriteStartElement("appSettings")

        For i As Integer = 0 To m_settings.Count - 1
            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()
        Next

        tw.WriteEndElement()
        tw.WriteEndElement()

        tw.Close()
    End Sub

End Class

GeneralA misprint Pin
Alexey Mochalov21-Mar-04 20:47
Alexey Mochalov21-Mar-04 20:47 
GeneralRe: A misprint Pin
pbrooks22-Mar-04 4:07
pbrooks22-Mar-04 4:07 

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

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