Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / Visual Basic
Article

Save and Restore User Preferences

Rate me:
Please Sign up or sign in to vote.
4.53/5 (19 votes)
15 Jan 2004CPOL3 min read 153.9K   1.4K   75   21
Persist virtually any information (including user defined structures, enums, object, etc.), per user.

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:

  • IConvertable is implemented by all "primatives" and enumerations, and identifies something that can be converted directly to a string and back.
  • ISerializable is implemented by a variety of objects, including Font, Image, Icon, and DataSet. It provides methods for converting an object to a stream (serialize) and back again (deserialize). Additionally, any structure with the <Serializable()> attribute can also be serialized, such as Color or Point.

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.

VB
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:

VB
Public Shared Function GetPreference(ByVal Key As String, 
                                  ByVal DefaultValue As Object) As Object
  • Key is the unique identifier for the preference
  • DefaultValue is the value to return if no saved preference can be found.

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.

VB
Public Shared Sub SavePreference(ByVal Key As String, ByVal Value As Object, 
                                                    ByVal Persist As Boolean)
  • Key is the unique identifier for the preference
  • Value is the value to be saved
  • Persist determines if the value is saved between sessions (True), or only stored in memory while the application is running (False).

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

VB
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.

VB
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
VB
Public Shared Sub FetchPreferences(Optional ByVal FileName As String = "")
  • FileName is the filename to use (or DefaultFileName, if not provided).

Loads in all user preferences saved in the specified file.

VB
Public Shared Sub SavePreferences(Optional ByVal FileName As String = "")
  • FileName is the Filename to use (or DefaultFileName, if not provided).

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:

VB
Protected Overridable Sub OnLoadSettings()

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

VB
Protected Overridable Sub OnSaveSettings()

Called when the form is closing.

VB
Protected Overridable Sub OnRendered()

Called when the form is first made visible.

VB
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

  • 1 Nov 2003 - udpated sourcecode
  • 16 Jan 2004 - updated sourcecode

License

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


Written By
Team Leader
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalsimple use :: Pin
pipiscrew25-Oct-07 1:35
pipiscrew25-Oct-07 1:35 
GeneralVersioning Problems when strong named Pin
davidko31-Mar-05 5:12
davidko31-Mar-05 5:12 
GeneralRe: Versioning Problems when strong named Pin
GWSyZyGy7-Apr-05 4:10
GWSyZyGy7-Apr-05 4:10 
GeneralExcellent class Pin
moldie5-Feb-04 23:26
moldie5-Feb-04 23:26 
An excellent class that works well. I'm a newbie to VB.Net on the learning curve so I had a go at I modifing your class to save application prefrences into an XML file, for instance app.site.config, strings and integers are no problem but anything else gives me grief. Any pointers

Many thanks
oldie_the_geordie Big Grin | :-D
GeneralRe: Excellent class Pin
GWSyZyGy6-Feb-04 4:08
GWSyZyGy6-Feb-04 4:08 
GeneralWorking with exceptions ... Pin
Sebastien Lorion17-Jan-04 7:12
Sebastien Lorion17-Jan-04 7:12 
GeneralLego rebuilds the planet within miniature Pin
Member 1080034620-Jan-04 4:52
Member 1080034620-Jan-04 4:52 
GeneralRe: Working with exceptions ... Pin
Sebastien Lorion20-Jan-04 17:02
Sebastien Lorion20-Jan-04 17:02 
GeneralError when returning empty strings! Pin
Member 9536214-Dec-03 12:55
Member 9536214-Dec-03 12:55 
GeneralRe: Error when returning empty strings! Pin
GWSyZyGy14-Jan-04 9:00
GWSyZyGy14-Jan-04 9:00 
GeneralSave/restore to SQL Server Pin
zsidi26-Nov-03 0:19
zsidi26-Nov-03 0:19 
GeneralRe: Save/restore to SQL Server Pin
GWSyZyGy3-Dec-03 5:25
GWSyZyGy3-Dec-03 5:25 
GeneralIt does not save Serializable objects Pin
I G 19829-Sep-03 3:33
I G 19829-Sep-03 3:33 
GeneralRe: It does not save Serializable objects Pin
GWSyZyGy24-Oct-03 11:22
GWSyZyGy24-Oct-03 11:22 
GeneralInteresting Pin
Nick Parker19-Jul-03 4:29
protectorNick Parker19-Jul-03 4:29 
GeneralRe: Interesting Pin
GWSyZyGy21-Jul-03 4:24
GWSyZyGy21-Jul-03 4:24 
GeneralRe: Interesting Pin
kbuchan22-Jul-03 2:04
kbuchan22-Jul-03 2:04 
GeneralRe: Interesting Pin
bigfoot10423-Jul-03 4:26
bigfoot10423-Jul-03 4:26 
GeneralRe: Interesting Pin
GWSyZyGy23-Jul-03 4:49
GWSyZyGy23-Jul-03 4:49 
GeneralRe: Interesting Pin
GWSyZyGy23-Jul-03 4:55
GWSyZyGy23-Jul-03 4:55 
GeneralRe: Interesting Pin
GWSyZyGy24-Jul-03 4:08
GWSyZyGy24-Jul-03 4:08 

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.