Skip to main content
Email Password   helpLost your password?

Sample Image

Introduction

This is my first article. I hope that my code and findings are helpful to other members of The Code Project. Much of this work was done as a learning experience. Did my best to comment the code to support NDoc.

Most of my programs are small utilities with just a few settings that I would like to persist. Things like the items in a ListBox or the selections made in a TreeView etc...

In the past, I have used the Win32 WritePrivateProfileString, GetPrivateProfileString or a file of my own making. So when it was time to learn .NET, one of the first things I wanted was a simple way to save my settings. When I didn't find what I wanted, I decided to write a DLL to use in all my programs. My first impression with the .NET Framework was how extensive it was. So I hope I haven't re-invented a wheel here.

My options to save settings seemed to be:

The Code Project was the first place I looked for some help on this topic and I found lots of it. Much of it used the XmlSerializer. After working with this class a bit, it seemed a little overkill so I decided not to use it. The XmlSerializer seems to take a while to load and still did not handle all my data types the way I wanted (like Color). If I knew the exact structure and type of my data at design time, it may be a good solution.

Because the user may want to save many different data types, it seemed that an Object type was the way to go. Normally, I would never even think of using an Object, but speed is not an issue here.

The trouble with the Object is all that casting. Having the user (me) explicitly cast the return value each time would be a pain.

Example

int ret = (int)MyIni.Sections["FormSettings"]["Left"];

The plan was to determine the data type when the user sets the value, and then save that type in the XML file. Then when you read the data back, just use an implicit cast to return it to the original type.

Example

int ret = MyIni.Sections["FormSettings"]["Left"];

Normally, an implicit cast is a bad thing. Implicit conversions can occur without the programmer specifying them, so care must be taken to prevent unpleasant surprises. In this case, we know the original type because we saved it when we set the value. So it seems safe. Plus, you could always get to the original Object by using the "Value" property of the setting.

Example

object ret = MyIni.Sections["FormSettings"]["Left"].Value;

Having said that, with the new Generics feature, this may change. Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR). They are somewhat like Class Templates in C++.

This is a sample of one of the overloaded operators to cast to bool. If you try to set a value of a type different than the original, it will throw an error.

public static implicit operator bool(IniSetting v)
{
    if(v.settingType!=Types.BOOLEAN)
    {
     throw new Exception("No conversion from " + v.settingType + " to bool." );
    }
    return (bool)v.settingValue;
}

Using the code

AppSettings class has the following members:

To use the DLL, just make a reference to it and use the following syntax:

//Try to load the settings bool loaded = MyIni.Load([File]); 

//Get the color of the form. It will be created 

//only if needed, using the current value. 

BackColor = MyIni.GetVal("FormSettings","BackColor",BackColor); 
//Font of the form. It will be created only if needed. 

Font = MyIni.GetVal("FormSettings","Font",Font); 
//Size of the form. It will be created only if needed 

Size = MyIni.GetVal("FormSettings","Size",Size);
//Notice in the following code that we do not have to cast the return value;

MyIni.SetVal("FormSettings","Left",Left);
//Return the same value with 2 different notations.

int ret = MyIni.GetVal("FormSettings","Left");
ret = MyIni.Sections["FormSettings"]["Left"];
//Save the settings

MyIni.Save([File]);

After the core functionality was finished, a utility class was created to handle more complicated settings. The overloaded methods static bool SaveItemsAndValues and static bool LoadItemsAndValues were added. It currently supports ComboBox, ListBox and TreeView. Sample code is provided for each.

At this point, the functionality is much like the old INI files. You have to write code to read each setting when a form is opened, and then write code to save the settings when the form is closed. That's not too bad but it could be better.

The ability to mark a particular property to be saved and add it to a list would be cool. That way, you could just tell the program to save all the marked properties when you close the form. You could use "Dynamic Properties" to save the settings to the app.config file but I chose not to interfere with that built-in functionality.

Somehow, I needed to save a reference to a control and one of its properties. Saving the name of a control and a property to XML is no problem. Getting a reference to an instance of a control at run time was the problem. This was done with Reflection. In case Reflection is new to you (it was (is) to me), Reflection provides a way to discover everything about an assembly or module. It also provides a way to do late binding and to invoke a method dynamically. This is what I needed. These are the static methods that achieve this.

Points of Interest

The PropertyGrid support was created with lots of help from CP contributors. I only have a basic understanding of the mechanism. The PropertyGrid will be a great interface for editing values.

The code uses #region PropertyGrid Support to identify code specific to the PG. Other than that, there are two extra PropertyDescriptor classes to support collections in the PG. Any suggestions for better PropertyGrid support is welcome.

Resources Used

History

Running the test program

  1. Start the program and click LoadTestData.
  2. Check some items in the tree and make some other changes.
  3. Click SaveCtrlsToSettings. This saves the tree and combo to the settings but not to disk.
  4. Click SaveSettingsToDisk. This saves the settings to disk.
  5. Close the program.
  6. Start the program and click LoadSettingsFromDisk. You should see your settings come back.
  7. Click LoadJasonsSettings. You should see My sample settings.
You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Generalhelp for my cnc projectt Pin
raheel189
4:51 7 Nov '09  
QuestionCould you tell me what license your code is released under? Pin
Noobsa44
13:58 16 Aug '09  
AnswerRe: Could you tell me what license your code is released under? Pin
Jason Titcomb
2:26 22 Aug '09  
GeneralSuggested fix in Settings.cs Pin
apuchacha
19:48 5 Jul '08  
GeneralHow did you get the Property Grid to Nest Pin
Luckymmkay
11:39 14 Dec '07  
GeneralRe: How did you get the Property Grid to Nest Pin
ByteGhost
16:02 23 Dec '07  
GeneralXML Serialization Pin
BoneSoft
10:43 1 May '07  
GeneralSuggested fix Pin
curiousharry
9:25 17 Apr '07  
GeneralRe: Suggested fix Pin
Jason Titcomb
12:38 20 Apr '07  
QuestionBug in AppSettings Pin
DIWIN
0:22 6 Feb '07  
AnswerRe: Bug in AppSettings Pin
Jason Titcomb
12:47 20 Apr '07  
GeneralSmall Bug in AppSettings Pin
gbalog
0:59 9 Nov '06  
GeneralError in loading settings that contain enumeration types Pin
xezero@gmail.com
10:58 19 Jun '06  
GeneralRe: Error in loading settings that contain enumeration types Pin
mad-matt
10:29 31 Mar '09  
GeneralPro for Registry Settings Pin
thx1200
9:58 19 Jun '06  
Generalanother ready-to-use solution Pin
Edwin Roetman
0:33 21 Mar '06  
Generalthanks Pin
NightJammer
9:39 18 Mar '06  
GeneralAnother fix and another typo Pin
Perry2
5:39 7 Mar '06  
Generaloutstanding bugs? Pin
Perry2
5:22 7 Mar '06  
AnswerRe: outstanding bugs? Pin
Kato
3:14 12 Mar '06  
GeneralPortability of SaveSettingsToXml files across locales Pin
Fred Thomas
5:46 21 Aug '05  
GeneralRe: Portability of SaveSettingsToXml files across locales Pin
JasonT61
1:40 23 Aug '05  
GeneralSingleton Pin
Kith Kahnan
15:00 8 Aug '05  
GeneralRe: Singleton Pin
JasonT61
1:33 23 Aug '05  
GeneralBug in new version? Pin
Doncp
7:29 25 Feb '05  


Last Updated 24 Apr 2007 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2009