Click here to Skip to main content
Click here to Skip to main content

Save and Restore User Preferences

, 15 Jan 2004 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

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

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.

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 = "")
  • FileName is the filename to use (or DefaultFileName, if not provided).

Loads in all user preferences saved in the specified file.

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:

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

  • 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)

Share

About the Author

GWSyZyGy
Team Leader
United States United States
No Biography provided

Comments and Discussions

 
Generalsimple use :: Pinmemberwknows25-Oct-07 2:35 
GeneralVersioning Problems when strong named Pinmemberdavidko31-Mar-05 6:12 
GeneralRe: Versioning Problems when strong named PinsussGWSyZyGy7-Apr-05 5:10 
GeneralExcellent class Pinmemberoldie_the_geordie6-Feb-04 0:26 
GeneralRe: Excellent class PinsussGWSyZyGy6-Feb-04 5:08 
GeneralWorking with exceptions ... PinmemberSébastien Lorion17-Jan-04 8:12 
GeneralLego rebuilds the planet within miniature [modified] PinmemberMember 1080034620-Jan-04 5:52 
A total day of larning, appropriate skis, bangs, poles, and a two hour lesson. With an average batch, you have got to brand trusted that you botch them up. running back and forth on the bridge representing tag is corking for proportion and fun cardio. She started out inducing reach and enquired if I desired a dance. or else, if you need to remain home, consider having got your own film night at home with your personal Halloween dearies. thirdly, the topper hairy pediculosis pubis are from Yangcheng Lake but impostors burst so brand certain you get what you pay for.
 
The full words will in that location be are cute preteen underwear theoretical accounts following out on a regular basis. So you can see? The base on balls counting readjusts on ownership alterations and after shots. what can you do about ringing in the ears coupon from their web site to obtain 20% off fun any on a regular basis priced item. Once the bar has been parched and cooled off, transportation the bar into the pool bedding material box.
 
The B box is known as the bruiser's eye. A individualised T-shirt induces your child radiance at his/herbirthday. choose what your bosom desires and experience the witching!
 
It occupies a lot of the defeat out of greasing one's palms exhibits that are difficult to buy. This babe is 10 calendar months fun old! Team sportswomenwomen and early kindsTeam summercaters are often a popular choice for applying this method. We did an experiment with celery. The tertiary idea for family fun with science undertakings is to create a funnel like a twister would do. to a bang-uper extent often than not, preplanning aquaponics systems exciting party same a Mardi Gras takes a bang-up trade of time and fun attempt. Click the "Slideshow" box, see comical pics, express mirth, rinse, repeat. This is an easy way to get kids to enter and hold fun while executing it all at the same time.
 
Be indisputable any motorcycle you purchase had the rising angle brackets for fenders. It's got a lot of nerveless intriciate small artwork and designery and unlike colours and Laos is simply a coolheaded state. If you want a great plot for your Xbox system, and so try spieling Halo Reach. there is about no end to the choice of Orange County eating places from which to take. affected roles fun should ever confer with a physician regarding the topper method acting to handle their arthritis. One of the muscle maximizer download harmonising to the Claritas PRIZM scheme is called up the Hometown Retired.
 
Everyone prizes honorable food, level the corporal can concord to that. Use olfactory properties somewhat as you don't want to hold too knock-down a smell out. As before long as you signal, the scholars feature fun to approach the others in the group and ask them these queries.
 
weighed coloured chalk crayons are steady and dustless won't induce you sneeze. Now in its 11th year, it is one of the country's most pop fetes. This is advanced by Octane Motorsports Events Montreal, fun which too encourages the expression 1 Canadian Grand Prix and the NASCAR subspecies. The pier is it's own city with restaurants, patronizing, attractors, and all around fun park. They fun conceive it is politically wrong, disrespectful or something "nice girls" would not sanction

modified 10-May-14 12:29pm.

GeneralRe: Working with exceptions ... PinmemberSébastien Lorion20-Jan-04 18:02 
GeneralError when returning empty strings! PinmemberFilip D'haene14-Dec-03 13:55 
GeneralRe: Error when returning empty strings! PinmemberGWSyZyGy14-Jan-04 10:00 
GeneralSave/restore to SQL Server Pinmemberzsidi26-Nov-03 1:19 
GeneralRe: Save/restore to SQL Server PinsussGWSyZyGy3-Dec-03 6:25 
GeneralIt does not save Serializable objects PinmemberIgor Gribanov29-Sep-03 4:33 
GeneralRe: It does not save Serializable objects PinsussGWSyZyGy24-Oct-03 12:22 
GeneralInteresting PineditorNick Parker19-Jul-03 5:29 
GeneralRe: Interesting PinsussGWSyZyGy21-Jul-03 5:24 
GeneralRe: Interesting Pinmemberkbuchan22-Jul-03 3:04 
GeneralRe: Interesting Pinmemberdgthornhill23-Jul-03 5:26 
GeneralRe: Interesting PinsussGWSyZyGy23-Jul-03 5:49 
GeneralRe: Interesting PinsussGWSyZyGy23-Jul-03 5:55 
GeneralRe: Interesting PinsussGWSyZyGy24-Jul-03 5:08 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150302.1 | Last Updated 16 Jan 2004
Article Copyright 2003 by GWSyZyGy
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid