This topic has not yet been rated - Rate this topic

ApplicationSettingsBase Class

Acts as a base class for deriving concrete wrapper classes to implement the application settings feature in Window Forms applications.

System.Object
  System.Configuration.SettingsBase
    System.Configuration.ApplicationSettingsBase

Namespace:  System.Configuration
Assembly:  System (in System.dll)
public abstract class ApplicationSettingsBase : SettingsBase, 
	INotifyPropertyChanged

The ApplicationSettingsBase type exposes the following members.

  Name Description
Protected method ApplicationSettingsBase() Initializes an instance of the ApplicationSettingsBase class to its default state.
Protected method ApplicationSettingsBase(IComponent) Initializes an instance of the ApplicationSettingsBase class using the supplied owner component.
Protected method ApplicationSettingsBase(String) Initializes an instance of the ApplicationSettingsBase class using the supplied settings key.
Protected method ApplicationSettingsBase(IComponent, String) Initializes an instance of the ApplicationSettingsBase class using the supplied owner component and settings key.
Top
  Name Description
Public property Context Gets the application settings context associated with the settings group. (Overrides SettingsBase.Context.)
Public property IsSynchronized Gets a value indicating whether access to the object is synchronized (thread safe). (Inherited from SettingsBase.)
Public property Item Gets or sets the value of the specified application settings property. (Overrides SettingsBase.Item[String].)
Public property Properties Gets the collection of settings properties in the wrapper. (Overrides SettingsBase.Properties.)
Public property PropertyValues Gets a collection of property values. (Overrides SettingsBase.PropertyValues.)
Public property Providers Gets the collection of application settings providers used by the wrapper. (Overrides SettingsBase.Providers.)
Public property SettingsKey Gets or sets the settings key for the application settings group.
Top
  Name Description
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetPreviousVersion Returns the value of the named settings property for the previous version of the same application.
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method Initialize Initializes internal properties used by SettingsBase object. (Inherited from SettingsBase.)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method OnPropertyChanged Raises the PropertyChanged event.
Protected method OnSettingChanging Raises the SettingChanging event.
Protected method OnSettingsLoaded Raises the SettingsLoaded event.
Protected method OnSettingsSaving Raises the SettingsSaving event.
Public method Reload Refreshes the application settings property values from persistent storage.
Public method Reset Restores the persisted application settings values to their corresponding default properties.
Public method Save Stores the current values of the application settings properties. (Overrides SettingsBase.Save().)
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Public method Upgrade Updates application settings to reflect a more recent installation of the application.
Top
  Name Description
Public event PropertyChanged Occurs after the value of an application settings property is changed.
Public event SettingChanging Occurs before the value of an application settings property is changed.
Public event SettingsLoaded Occurs after the application settings are retrieved from storage.
Public event SettingsSaving Occurs before values are saved to the data store.
Top

ApplicationSettingsBase adds the following functionality to the SettingsBase class, which is used by Web-based applications:

  • The ability to detect attributes on a derived, settings wrapper class. ApplicationSettingsBase supports the declarative model used for wrapper class properties, as described later.

  • Higher-level Save and Reload methods.

  • Additional validation events that you can handle to ensure the correctness of individual settings.

In the application settings architecture, to access a group of settings properties you need to derive a concrete wrapper class from ApplicationSettingsBase. The wrapper class customizes ApplicationSettingsBase in the following ways:

  • For every settings property to be accessed, a corresponding strongly typed public property is added to the wrapper class. This property has get and set accessors for read/write application settings, but only a get accessor for read-only settings.

  • Appropriated attributes must be applied to the wrapper class's public properties to indicate characteristics of the settings property, such as the setting's scope (application or user), whether the setting should support roaming, the default value for the setting, the settings provider to be used, and so on. Each property is required to specify its scope, using either ApplicationScopedSettingAttribute or UserScopedSettingAttribute. Application-scoped settings are read-only if the default LocalFileSettingsProvider is used.

The ApplicationSettingsBase class uses reflection to detect these attributes at run time. Most of this information gets passed to the settings provider layer, which is responsible for storage, persistence format, and so on.

When an application has multiple settings wrapper classes, each class defines a settings group. Each group has the following characteristics:

  • A group can contain any number or type of property settings.

  • If the group name is not explicitly set by the decorating the wrapper class with a SettingsGroupNameAttribute, then a name is automatically generated.

By default, all client-based applications use the LocalFileSettingsProvider to provide storage. If an alternate settings provider is desired, then the wrapper class or property must be decorated with a corresponding SettingsProviderAttribute.

For more information about using application settings, see Application Settings for Windows Forms.

The following code example demonstrates the use of application settings to persist the following attributes of the main form: location, size, background color, and title bar text. All of these attributes are persisted as single application settings properties in the FormSettings class, named FormLocation, FormSize, FormBackColor and FormText, respectively. All except for FormText and Size are data bound to their associated form properties and have a default setting value applied using DefaultSettingValueAttribute.

The form contains four child controls that have the following names and functions:

  • A button named btnBackColor used to display the Color common dialog box.

  • A button named btnReload used to Reload the application settings.

  • A button named btnReset used to Reset the application settings.

  • A textbox named tbStatus used to display status information about the program.

Notice that after every execution of the application, an additional period character is appended to the title text of the form.

This code example requires a Form with a ColorDialog class named colorDialog1, and a StatusStrip control with a ToolStripStatusLabel named tbStatus. Additionally, it requires three Button objects named btnReload, btnReset, and btnBackColor.


   partial class Form1 : Form
   {
       private FormSettings frmSettings1 = new FormSettings();

       public Form1()
       {
           InitializeComponent();
       }

       private void Form1_Load(object sender, EventArgs e)
       {
           this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);

           //Associate settings property event handlers.
           frmSettings1.SettingChanging += new SettingChangingEventHandler(
                                               frmSettings1_SettingChanging);
           frmSettings1.SettingsSaving += new SettingsSavingEventHandler(
                                               frmSettings1_SettingsSaving);

           //Data bind settings properties with straightforward associations.
           Binding bndBackColor = new Binding("BackColor", frmSettings1, 
               "FormBackColor", true, DataSourceUpdateMode.OnPropertyChanged);
           this.DataBindings.Add(bndBackColor);
           Binding bndLocation = new Binding("Location", frmSettings1, 
               "FormLocation", true, DataSourceUpdateMode.OnPropertyChanged);
           this.DataBindings.Add(bndLocation);

           // Assign Size property, since databinding to Size doesn't work well.
            this.Size = frmSettings1.FormSize;

           //For more complex associations, manually assign associations.
           String savedText = frmSettings1.FormText;
           //Since there is no default value for FormText.
           if (savedText != null)
               this.Text = savedText;
       }

       private void Form1_FormClosing(object sender, FormClosingEventArgs e)
       {
           //Synchronize manual associations first.
           frmSettings1.FormText = this.Text + '.';
           frmSettings1.FormSize = this.Size;
           frmSettings1.Save();
       }

       private void btnBackColor_Click(object sender, EventArgs e)
       {
           if (DialogResult.OK == colorDialog1.ShowDialog())
           {
               Color c = colorDialog1.Color;
               this.BackColor = c;
           }
       }

       private void btnReset_Click(object sender, EventArgs e)
       {
           frmSettings1.Reset();
           this.BackColor = SystemColors.Control;
       }

       private void btnReload_Click(object sender, EventArgs e)
       {
           frmSettings1.Reload();
       }

       void frmSettings1_SettingChanging(object sender, SettingChangingEventArgs e)
       {
           tbStatus.Text = e.SettingName + ": " + e.NewValue;
       }

       void frmSettings1_SettingsSaving(object sender, CancelEventArgs e)
       {
           //Should check for settings changes first.
           DialogResult dr = MessageBox.Show(
                           "Save current values for application settings?",
                           "Save Settings", MessageBoxButtons.YesNo);
           if (DialogResult.No == dr)
           {
               e.Cancel = true;
           }
       }

   }

   //Application settings wrapper class
   sealed class FormSettings : ApplicationSettingsBase
   {
       [UserScopedSettingAttribute()]
       public String FormText
       {
           get { return (String)this["FormText"]; }
           set { this["FormText"] = value; }
       }

       [UserScopedSettingAttribute()]
       [DefaultSettingValueAttribute("0, 0")]
       public Point FormLocation
       {
           get { return (Point)(this["FormLocation"]); }
           set { this["FormLocation"] = value; }
       }

       [UserScopedSettingAttribute()]
       [DefaultSettingValueAttribute("225, 200")]
       public Size FormSize
       {
           get { return (Size)this["FormSize"]; }
           set { this["FormSize"] = value; }
       }


       [UserScopedSettingAttribute()]
       [DefaultSettingValueAttribute("LightGray")]
       public Color FormBackColor
       {
           get { return (Color)this["FormBackColor"]; }
           set { this["FormBackColor"] = value; }
       }

   }



.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
using System.Configuration seems not to be enough for FormSettings
Hello!

I am new to this subject and try to find reliable information concerning saving location and size information in a Windows Forms project. I tried to make the example run, but rather cannot even compile because FormSettings cannot be found. The line


using System;
using System.Configuration;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsLocationSize
{
  public partial class Form1 : Form
  {
    private FormSettings frmSettings1 = new FormSettings();    // <<<<<<
    [...]

... is rejected with the error message: "The type of namespace name "FormSettings" could not be found. (Is a using directive or an assembly link missing?)"

I could not find any detailed description of the "class" FormSettings. How am I supposed to write the code?

Thanks!

Ok - I can't get any of this to work.
Well that's not strictly true, I can read in default values from my derived class,
but that's it.
I'm using a console Application, and VS2010 Express, maybe that's my problem.

I have the 'using System.Configuration;' and the correct dll.
However the 'intillisense' does not give a Method 'Save' for:

ApplicationSettingsBase
SettingsBase
or off my derived class as shown in the main example.

Windows 'Form's are just an unnecessary complication when one is giving an example of usage of a class.


Example works, but...
Code based on the example does not work with properties that return value types. To get it to work, make sure your new property returns types that are nullable. For example:
       [UserScopedSettingAttribute()]
       public int? MyIntValue
       {
           get { return (int?)this["MyIntValue"]; }
           set { this["MyIntValue"] = value; }
       }

The example works
The example needs "using System.Configuration;" to be added
This above example does not seem to work!
I followed the above insturction to a T and although it looks like the program is saving the APP settings, it actually does not.  There seems to be a setting or some code linking it alltogether for it to work.