Skip to main content
Email Password   helpLost your password?

Screen Shot

Introduction

There are several samples available to save and restore application or user preferences, but most are limited to primatives (numbers, dates, booleans, strings, etc.), or have code to handle specific types of objects. I found this approach too limiting, and frankly, too complex for what is a fairly simple operation - convert _X_ to a string and back again.

The answer lies mainly in two built-in interfaces:

Background

This sample is built around actual production code that I use, to save user preferences to a SQL Server database. The code in the demo was modified to simply use text files.

Using the code

Sample Code

The following excerpts from the demo code show, how easy it is to save and restore various user preferences: a Color, a Font, and a String. The demo will also demonstrate an Enum (CheckState), a DateTime, an Image, and a user-defined Structure (via frmWindowSettings). Move the form, resize it -- it will appear the same the next time you run the application.

Protected Overrides Sub OnLoadSettings()
    ' Let mybase do its thing...


    MyBase.OnLoadSettings()

    ' Load my form's data:

    ' TextBox attributes: text (String), font (Object), color (Structure)

    tbFreeForm.ForeColor = CType(UserPreferences.GetPreference
                ("FREEFORM.COLOR", tbFreeForm.ForeColor), Color)
    tbFreeForm.Font = CType(UserPreferences.GetPreference
                ("FREEFORM.FONT", tbFreeForm.Font), Font)
    tbFreeForm.Text = CType(UserPreferences.GetPreference
                ("FREEFORM.TEXT", tbFreeForm.Text), String)
End Sub

Protected Overrides Sub OnSaveSettings()
    ' Let mybase do its thing...

    MyBase.OnSaveSettings()

    ' Save my form's data:

    UserPreferences.SavePreference("FREEFORM.COLOR", 
                             tbFreeForm.ForeColor, True)
    UserPreferences.SavePreference("FREEFORM.FONT", tbFreeForm.Font, True)
    UserPreferences.SavePreference("FREEFORM.TEXT", tbFreeForm.Text, True)

    ' Since this is the "main" window, now we

    ' tell UserPrefs to actually save:

    UserPreferences.SavePreferences()
End Sub

UserPreferences

The UserPreferences class has several static (Shared) methods:

Public Shared Function GetPreference(ByVal Key As String, 
                                  ByVal DefaultValue As Object) As Object

Returns a saved preference (if found), or the provided DefaultValue. The Type of the DefaultValue must match the type of the saved preference -- it is used to determine how to restore the saved value.

Public Shared Sub SavePreference(ByVal Key As String, ByVal Value As Object, 
                                                    ByVal Persist As Boolean)

Saves the specified value to the local cache; will optionally flag persistence to a file.

Public Shared Property AutoSave() As Boolean

Sets the save mode for the UserPreferences: Use AutoSave = True to enable atomic (key/value) saves, each time SavePreference is called. Use AutoSave = False to use the bulk save method. The demo only supports AutoSave = False.

Public Shared Function DefaultFileName() As String

Returns the default filename used to save/load user preferences. It will be in the format:

x:\Documents and Settings\<username>\Application Data\
                                <exename>\Preferences.dat
Public Shared Sub FetchPreferences(Optional ByVal FileName As String = "")

Loads in all user preferences saved in the specified file.

Public Shared Sub SavePreferences(Optional ByVal FileName As String = "")

Saves all user preferences to the specified file.

frmWindowSettings

Also included is an ancestor form, that automatically saves and restores its last size, position, and state. I use this form as an inheritance base, whenever creating a new window. It provides custom "events" to easily add load/save code, as well as a new property:

Protected Overridable Sub OnLoadSettings()

Called when the form and controls have been created and initialized.

Protected Overridable Sub OnSaveSettings()

Called when the form is closing.

Protected Overridable Sub OnRendered()

Called when the form is first made visible.

Public Property SaveSettings() As Boolean

Set True to enable window size/position restore (default); set False to disable. SaveSettings = False will not disable OnSaveSettings or OnLoadSettings, just the ancestor behavior.

Points of interest

When developing the routines, I found that DateTime is not 100% "convertible." When a DateTime is converted to a String, only seconds are kept, and any fractions are discarded. To prevent data loss, DateTime values are stored as ticks (1/10,000 sec.) in SavePreference().

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Generalsimple use :: Pin
wknows
2:35 25 Oct '07  
GeneralVersioning Problems when strong named Pin
davidko
6:12 31 Mar '05  
GeneralRe: Versioning Problems when strong named Pin
GWSyZyGy
5:10 7 Apr '05  
GeneralExcellent class Pin
oldie_the_geordie
0:26 6 Feb '04  
GeneralRe: Excellent class Pin
GWSyZyGy
5:08 6 Feb '04  
GeneralWorking with exceptions ... Pin
Sébastien Lorion
8:12 17 Jan '04  
GeneralRe: Working with exceptions ... Pin
GWSyZyGy
5:52 20 Jan '04  
GeneralRe: Working with exceptions ... Pin
Sébastien Lorion
18:02 20 Jan '04  
GeneralError when returning empty strings! Pin
Filip D'haene
13:55 14 Dec '03  
GeneralRe: Error when returning empty strings! Pin
GWSyZyGy
10:00 14 Jan '04  
GeneralSave/restore to SQL Server Pin
zsidi
1:19 26 Nov '03  
GeneralRe: Save/restore to SQL Server Pin
GWSyZyGy
6:25 3 Dec '03  
GeneralIt does not save Serializable objects Pin
Igor Gribanov
4:33 29 Sep '03  
GeneralRe: It does not save Serializable objects Pin
GWSyZyGy
12:22 24 Oct '03  
GeneralInteresting Pin
Nick Parker
5:29 19 Jul '03  
GeneralRe: Interesting Pin
GWSyZyGy
5:24 21 Jul '03  
GeneralRe: Interesting Pin
kbuchan
3:04 22 Jul '03  
GeneralRe: Interesting Pin
dgthornhill
5:26 23 Jul '03  
GeneralRe: Interesting Pin
GWSyZyGy
5:49 23 Jul '03  
GeneralRe: Interesting Pin
GWSyZyGy
5:55 23 Jul '03  
GeneralRe: Interesting Pin
GWSyZyGy
5:08 24 Jul '03  


Last Updated 15 Jan 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2009